在一行中:给定一个字符串,我们如何获得它的原始字符串表示?
我正在生成一个文件,其中有正则表达式,如'[ \\n\\t\\r\\f\\v]'
,我希望将其作为原始字符串呈现。如何实现这一目标?
P.S:我实际上打算用双引号表示字符串,因此字符串'\''
呈现为"'"
。我也需要帮助..
“raw string”我指的是我们常用于regexp的字符串类型:
>>> r"[ \r\n\f\v\t]"
'[ \\r\\n\\f\\v\\t]'
# assuming to_raw is the function
>>> print to_raw(r"[ \r\n\f\v\t]")
r'[ \r\n\f\v\t]'
>>> print to_raw("\\\\")
r'\\'
>>> print to_raw("'")
r"'"
答案 0 :(得分:3)
如果您的字符串来自原始字符串,则它会显示在r''
,r""
,r''''''
或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
答案 1 :(得分:1)
在一行中:给定一个字符串,我们如何获得原始字符串 它的代表?
原始字符串只是转义任何特殊序列:
>>> s
'This is some string \n that is not \raw'
>>> print(s)
This is some string
awhat is not
>>> i = s.encode('string_escape')
>>> i
'This is some string \\n that is not \\raw'
>>> print(i)
This is some string \n that is not \raw
>>> i == r'This is some string \n that is not \raw'
True
>>> i == s
False