使用 Python 3.2 对字符串中的转义字符进行转义 [英] Unescaping escaped characters in a string using Python 3.2
问题描述
假设我在 Python 3.2 中有一个这样的字符串:
'\n'
当我将它打印()到控制台时,它显然显示为一个新行.我想要的是能够将它从字面上打印为反斜杠后跟 n.此外,我需要对所有转义字符执行此操作,例如 \t.所以我正在寻找一个函数 unescape(),对于一般情况,它的工作方式如下:
<预><代码>>>>s = '\n\t'>>>打印(取消转义)'\\n\\t'这在 Python 中是否可行,而无需为它们的字面替换构建转义字符字典?
(如果有人感兴趣,我这样做的原因是因为我需要在命令行上将字符串传递给外部程序.该程序理解所有标准转义序列.)
为了防止对文字字符串中的 \
进行特殊处理,您可以使用 r
前缀:
s = r'\n'印刷)# ->\n
如果您有一个包含换行符 (ord(s) == 10
) 的字符串,并且您想将其转换为适合作为 Python 文字的形式:
s = '\n's = s.encode('unicode-escape').decode()印刷)# ->\n
Say I have a string in Python 3.2 like this:
'\n'
When I print() it to the console, it shows as a new line, obviously. What I want is to be able to print it literally as a backslash followed by an n. Further, I need to do this for all escaped characters, such as \t. So I'm looking for a function unescape() that, for the general case, would work as follows:
>>> s = '\n\t'
>>> print(unescape(s))
'\\n\\t'
Is this possible in Python without constructing a dictionary of escaped characters to their literal replacements?
(In case anyone is interested, the reason I am doing this is because I need to pass the string to an external program on the command line. This program understands all the standard escape sequences.)
To prevent special treatment of \
in a literal string you could use r
prefix:
s = r'\n'
print(s)
# -> \n
If you have a string that contains a newline symbol (ord(s) == 10
) and you would like to convert it to a form suitable as a Python literal:
s = '\n'
s = s.encode('unicode-escape').decode()
print(s)
# -> \n
这篇关于使用 Python 3.2 对字符串中的转义字符进行转义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!