简体   繁体   English

Unescaping使用Python 3.2转义字符串中的字符

[英]Unescaping escaped characters in a string using Python 3.2

Say I have a string in Python 3.2 like this: 假设我在Python 3.2中有一个字符串,如下所示:

'\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. 我想要的是能够打印它作为反斜杠后跟一个n。 Further, I need to do this for all escaped characters, such as \\t. 此外,我需要为所有转义字符执行此操作,例如\\ t。 So I'm looking for a function unescape() that, for the general case, would work as follows: 所以我正在寻找一个函数unescape(),对于一般情况,它将按如下方式工作:

>>> s = '\n\t'
>>> print(unescape(s)) 
'\\n\\t'

Is this possible in Python without constructing a dictionary of escaped characters to their literal replacements? 这可能在Python中没有构建转义字符的字典到它们的字面替换吗?

(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: 为了防止在文字字符串中对\\进行特殊处理,你可以使用r前缀:

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: 如果你有一个包含换行符号的字符串( ord(s) == 10 )并且你想将它转换为适合Python文字的形式:

s = '\n'
s = s.encode('unicode-escape').decode()
print(s)
# -> \n

Edit: Based on your last remark, you likely want to get from Unicode to some encoded representation. 编辑:根据您的上一条评论,您可能希望从Unicode获得某些编码表示。 This is one way: 这是一种方式:

>>> s = '\n\t'
>>> s.encode('unicode-escape')
b'\\n\\t'

If you don't need them to be escaped then use your system encoding, eg: 如果您不需要转义它们,请使用您的系统编码,例如:

>>> s.encode('utf8')
b'\n\t'

You could use that in a subprocess: 您可以在子进程中使用它:

import subprocess
proc = subprocess.Popen([ 'myutility', '-i', s.encode('utf8') ], 
                        stdout=subprocess.PIPE, stdin=subprocess.PIPE, 
                        stderr=subprocess.STDOUT)
stdout,stderr = proc.communicate()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM