如果您的字符串来自原始字符串,它会出现在您的源代码中r''
, r""
, r''''''
, or内r""""""
,没有其他特殊转义。其中之一将起作用:
import ast
def rawstringify(s):
for format in ["r'{}'", 'r"{}"', "r'''{}'''", 'r"""{}"""']:
rawstring = format.format(s)
try:
reparsed = ast.literal_eval(rawstring)
if reparsed == s:
return rawstring
except SyntaxError:
pass
raise ValueError('rawstringify received an invalid raw string')
演示:
>>> print rawstringify(r'')
r''
>>> print rawstringify(r'\n\r\b\t')
r'\n\r\b\t'
>>> print rawstringify(r"'")
r"'"
>>> print rawstringify(r'\
... ')
r'\
'
>>> print rawstringify(r'''asdf
... ''')
r'''asdf
'''
>>> print rawstringify('\\')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 10, in rawstringify
ValueError: rawstringify received an invalid raw string