Reputation: 2347
The following shows what I want to do:
>>> "input '\t' quote tab".replace("'\\",'replace')
"input '\t' quote tab"
>>>
The output shows that the quote and backslash are not replaced.
I wonder why.
Upvotes: 1
Views: 130
Reputation: 152860
\t
is one character (as pointed out by @MaLiN2223). If you want it to be "raw" then you need to use raw strings:
>>> r"input '\t' quote tab".replace("'\\", 'replace')
"input replacet' quote tab"
The following "escaped sequences" are treated as one-character unless an 'r' or 'R' string is used (taken from the python3 documentation and the python2 equivalent):
\newline Ignored
\\ Backslash (\)
\' Single quote (')
\" Double quote (")
\a ASCII Bell (BEL)
\b ASCII Backspace (BS)
\f ASCII Formfeed (FF)
\n ASCII Linefeed (LF)
\N{name} Character named name in the Unicode database (Unicode only)
\r ASCII Carriage Return (CR)
\t ASCII Horizontal Tab (TAB)
\uxxxx Character with 16-bit hex value xxxx (Unicode only)
\Uxxxxxxxx Character with 32-bit hex value xxxxxxxx (Unicode only)
\v ASCII Vertical Tab (VT)
\ooo Character with octal value ooo
\xhh Character with hex value hh
Upvotes: 3
Reputation: 1298
I think this is because python desn't see this particual \
as \
but as part of \t
. And since \t
is single character, you cannot replace part of it.
Where as in this example:
"input '\t' quote tab'\\".replace("'\\",'replace')
Output will be:
"input '\t' quote tabreplace"
Upvotes: 2