如何防止在Python中自动转义特殊字符

pol*_*tr1 8 python escaping special-characters

我正在编写一个Python脚本,它接受文件路径作为字符串,解析它们,附加一个命令名,然后构建一个列表,然后传递给它subprocess.Popen()执行.此脚本用于处理Unix和Windows文件路径,最终应在两个系统上运行.

当我在Unix下运行时,如果我给出一个无意中包含转义字符的Windows路径(例如\Users\Administrator\bin),Python会将嵌入式解释\b为退格字符.我想防止这种情况发生.

据我所知,没有函数或方法将字符串变量表示为原始字符串.该'r'修饰符仅适用于字符串常量.

到目前为止,我能得到的最接近的是:

winpath = "C:\Users\Administrator\bin" 
winpath = winpath.replace('\b','\\b')
winpathlist = winpath.split('\\') 
Run Code Online (Sandbox Code Playgroud)

此时,winpathlist应该包含['C:','Users','Administrator','bin'],而不是['C','Users','Administrator\x08in'].

我可以添加额外的呼叫winpath.replace()处理等逃跑我可能会- ,\a,\f,\n,,\r -但不是.\t\v\x

是否有更多的pythonic方式来做到这一点?

Pie*_* GM 8

如果你winpath是硬编码的,你可能想r在字符串之前使用它来表明它是一个"原始字符串".

winpath = r"C:\Users\Administrator\bin"
Run Code Online (Sandbox Code Playgroud)

如果winpath无法硬编码,您可以尝试创建一个新字符串:

escaped_winpath = "%r" % winpath
Run Code Online (Sandbox Code Playgroud)

(这只是repr(winpath),并不会真正帮助你,因为repr("\bin")...)

解决方案是从头开始重建字符串:您可以在该链接上找到函数的示例,但通用的想法是:

escape_dict={'\a':r'\a',
             '\b':r'\b',
             '\c':r'\c',
             '\f':r'\f',
             '\n':r'\n',
             '\r':r'\r',
             '\t':r'\t',
             '\v':r'\v',
             '\'':r'\'',
             '\"':r'\"'}

def raw(text):
    """Returns a raw string representation of text"""
    new_string=''
    for char in text:
        try: 
            new_string += escape_dict[char]
        except KeyError: 
            new_string += char
    return new_string
Run Code Online (Sandbox Code Playgroud)

现在,raw("\bin")给你"\\bin"(而不是"\\x08in")......


the*_*oof 5

您可以通过在字符串文字符号前加r来创建原始字符串

r"hello\nworld"
Run Code Online (Sandbox Code Playgroud)

变成

"hello\\nworld"
Run Code Online (Sandbox Code Playgroud)

你可以在这里阅读更多