Skip to main content
 首页 » 编程设计

python之如何在 python 中替换引号反斜杠

2025年05月04日24zhenyulu

下面显示了我想做的事情:

>>> "input '\t' quote tab".replace("'\\",'replace') 
"input '\t' quote tab" 
>>> 

输出显示引号和反斜杠没有被替换。

我想知道为什么。

请您参考如下方法:

\t 是一个字符(正如@MaLiN2223 所指出的)。如果您希望它是“原始”的,那么您需要使用原始字符串:

>>> r"input '\t' quote tab".replace("'\\", 'replace') 
"input replacet' quote tab" 

除非使用 'r' 或 'R' 字符串(取自 python3 documentation 和 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