[英]Escape special characters in a Python string
Python 是否有一個 function 可以用來轉義字符串中的特殊字符?
例如, I'm "stuck":\
應該變成I\'m \"stuck\":\\
。
>>> import re
>>> re.escape(r'\ a.*$')
'\\\\\\ a\\.\\*\\$'
>>> print(re.escape(r'\ a.*$'))
\\\ a\.\*\$
>>> re.escape('www.stackoverflow.com')
'www\\.stackoverflow\\.com'
>>> print(re.escape('www.stackoverflow.com'))
www\.stackoverflow\.com
在這里重復:
re.escape(字符串)
返回所有非字母數字加反斜杠的字符串; 如果您想匹配其中可能包含正則表達式元字符的任意文字字符串,這將很有用。
從Python 3.7開始, re.escape()
已更改為僅轉義對正則表達式操作有意義的字符。
我很驚訝沒有人提到通過re.sub()
使用正則表達式:
import re
print re.sub(r'([\"])', r'\\\1', 'it\'s "this"') # it's \"this\"
print re.sub(r"([\'])", r'\\\1', 'it\'s "this"') # it\'s "this"
print re.sub(r'([\" \'])', r'\\\1', 'it\'s "this"') # it\'s\ \"this\"
重要注意事項:
\\
以及要查找的字符。 你會使用\\
逃脫你的角色,所以你需要逃避這一點。 ([\\"])
,以便替換模式在其前面添加\\
時可以使用找到的字符(這就是\\1
作用:使用第一個帶括號的組的值。 ) r
前面r'([\\"])'
意味着它是一個原始字符串 。原始字符串使用不同的規則轉義反斜線。要寫([\\"])
作為一個普通的字符串,你需要加倍所有反斜杠並寫'([\\\\"])'
。在編寫正則表達式時,原始字符串更友好。 \\
進行轉義以使其與替換組之前的反斜杠(例如\\1
,因此r'\\\\\\1'
區分開。 寫的,作為一個純字符串,你需要'\\\\\\\\\\\\1'
-大家都不希望發生。 使用repr()[1:-1]。 在這種情況下,雙引號不需要轉義。 [-1:1]切片將刪除開頭和結尾的單引號。
>>> x = raw_input()
I'm "stuck" :\
>>> print x
I'm "stuck" :\
>>> print repr(x)[1:-1]
I\'m "stuck" :\\
或者,也許您只是想轉義一個短語以粘貼到您的程序中? 如果是這樣,請執行以下操作:
>>> raw_input()
I'm "stuck" :\
'I\'m "stuck" :\\'
如上所述,答案取決於您的情況。 如果要轉義正則表達式的字符串,則應使用re.escape()。 但是,如果要轉義一組特定的字符,請使用此lambda函數:
>>> escape = lambda s, escapechar, specialchars: "".join(escapechar + c if c in specialchars or c == escapechar else c for c in s)
>>> s = raw_input()
I'm "stuck" :\
>>> print s
I'm "stuck" :\
>>> print escape(s, "\\", ['"'])
I'm \"stuck\" :\\
如果只想替換某些字符,則可以使用以下命令:
import re
print re.sub(r'([\.\\\+\*\?\[\^\]\$\(\)\{\}\!\<\>\|\:\-])', r'\\\1', "example string.")
這並不難:
def escapeSpecialCharacters ( text, characters ):
for character in characters:
text = text.replace( character, '\\' + character )
return text
>>> escapeSpecialCharacters( 'I\'m "stuck" :\\', '\'"' )
'I\\\'m \\"stuck\\" :\\'
>>> print( _ )
I\'m \"stuck\" :\
使用 json:
import json
print(r"""(I'm "stuck" :\)""") # (I'm "stuck" :\)
print(json.dumps(r"""(I'm "stuck" :\)""")) # (I'm "stuck" :\)
對於 json 到帶有轉義字符的字符串
json.dumps(json.dumps(d))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.