1

在一行中:给定一个字符串,我们如何获得它的原始字符串表示形式?


我正在生成一个文件,其中有正则表达式,'[ \\n\\t\\r\\f\\v]'我希望将其呈现为原始字符串。如何做到这一点?

PS:我实际上也打算用双引号表示字符串,所以字符串'\''呈现为"'". 我也需要这方面的帮助。。

“原始字符串”是指我们经常用于正则表达式的字符串类型:

>>> 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"'"
4

2 回答 2

3

如果您的字符串来自原始字符串,它会出现在您的源代码中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
于 2013-12-16T10:28:48.390 回答
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
于 2013-08-29T11:37:11.910 回答