How to prevent automatic escaping of special characters in Python

前端 未结 2 1752
野性不改
野性不改 2020-12-06 18:07

I\'m writing a Python script that accepts file paths as strings, parses them, appends a command name, and builds a list, which is then passed to subprocess.Popen()

相关标签:
2条回答
  • 2020-12-06 18:42

    If your winpath is hard-coded, you may want to use r before your string to indicate it is a "raw string".

    winpath = r"C:\Users\Administrator\bin"
    

    If winpath cannot be hardcoded, you can try to create a new string as:

    escaped_winpath = "%r" % winpath
    

    (which is just repr(winpath), and won't really help you, as repr("\bin") is...)

    A solution would be to rebuild the string from scratch: you can find an example of function at that link, but the generic idea is:

    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
    

    and now, raw("\bin") gives you "\\bin" (and not "\\x08in")...

    0 讨论(0)
  • 2020-12-06 18:43

    You can create a raw string by prepending r to the string literal notation

    r"hello\nworld"
    

    becomes

    "hello\\nworld"
    

    You can read some more here

    0 讨论(0)
提交回复
热议问题