Escape for str in Python

前端 未结 6 1449
星月不相逢
星月不相逢 2021-01-25 02:45

Wow, this should be so simple, but it\' just not working. I need to inset a \"\\\" into a string (for a Bash command), but escaping just doesn\'t work.

>>&         


        
相关标签:
6条回答
  • 2021-01-25 02:53

    'tes\\ting' is correct, but you are viewing the repr output for the string, which will always show escape characters.

    >>> print 'tes\\ting'
    tes\ting
    
    0 讨论(0)
  • 2021-01-25 02:58

    You are being misled by Python's output. Try:

    >>> a = "test\\ing"
    >>> print(a)
    test\ing
    >>> print(repr(a))
    'test\\ing'
    >>> a
    'test\\ing'
    
    0 讨论(0)
  • 2021-01-25 03:06

    If you want double slashes because the shell will escape \ again, use a raw string:

    b = a[:3] + r'\\' + a[3:]
    
    0 讨论(0)
  • 2021-01-25 03:08

    The second example is correct. There are two slashes because you are printing the Python representation of the string.

    If you want to see the actual string, call print a.

    0 讨论(0)
  • 2021-01-25 03:14

    b is fine in the second example, you see two slashes because you're printing the representation of b, so slashes are escaped in it too.

    >>> b
    'tes\\ting'
    >>> print b
    tes\ting
    >>> 
    
    0 讨论(0)
  • 2021-01-25 03:17

    Python's quoting the backslash again when it shows you the representation of the string (in such a way that you could paste it in and get the string with an escaped backslash).

    If you print the string, you'll see there's only one in the actual string.

    >>> print "hello\\world"
    hello\world
    
    0 讨论(0)
提交回复
热议问题