Python打印字符串就像一个原始字符串

Hao*_*ang 16 python

假设我从json获得了一个unicode字符串u'a\tb',如果是的话print,我会得到a b.但是我现在想要的是打印一个完全相同的字符串a\tb.我该怎么做?

Joh*_*nck 26

print(repr('a\tb'))
Run Code Online (Sandbox Code Playgroud)

repr() 为您提供字符串的"表示"而不是直接打印字符串.

  • @wyz23x2:确实如此,如果您不需要引号,则需要删除它们。 (2认同)

wyz*_*3x2 5

1:

(Python 2)

print ur'a\tb'
Run Code Online (Sandbox Code Playgroud)

请注意,在 Python 3.x 中,u''等于'',且前缀ur无效。
Python 3:

print(r'a\tb')
Run Code Online (Sandbox Code Playgroud)

2:

(Python 3)

print('a\\tb') 
Run Code Online (Sandbox Code Playgroud)

3:

如果你想获取现有字符串的原始表示,这里有一个小函数:(Python 3.6+)

def raw(string: str, replace: bool = False) -> str:
    """Returns the raw representation of a string. If replace is true, replace a single backslash's repr \\ with \."""
    r = repr(string)[1:-1]  # Strip the quotes from representation
    if replace:
        r = r.replace('\\\\', '\\')
    return r
Run Code Online (Sandbox Code Playgroud)

例子:

>>> print(raw('1234'))
1234
>>> print('\t\n'); print('='*10); print(raw('\t\n'))
    

==========
\t\n
>>> print(raw('\r\\3'))
\r\\3
>>> print(raw('\r\\3', True))
\r\3
Run Code Online (Sandbox Code Playgroud)

请注意,这不适用于\N{...}Unicode 转义,但r'\N{...}'只能如此。但我猜 JSON 没有这个:)

>>> print(raw('\N{PLUS SIGN}'))
+
Run Code Online (Sandbox Code Playgroud)