我需要做這個變量:使用 「R」 在應用re.sub
text = re.sub(r'\]\n', r']', text)
但隨着find
和replace
變量:
find = '\]\n'
replace = ']'
text = re.sub(find, replace, text)
我應該在哪裏把r
(原料)?它不是一個字符串。
我需要做這個變量:使用 「R」 在應用re.sub
text = re.sub(r'\]\n', r']', text)
但隨着find
和replace
變量:
find = '\]\n'
replace = ']'
text = re.sub(find, replace, text)
我應該在哪裏把r
(原料)?它不是一個字符串。
r''
的是string literal syntax的一部分:
find = r'\]\n'
replace = r']'
text = re.sub(find, replace, text)
的語法是決不特定於re
模塊。但是,指定正則表達式是原始字符串的主要用例之一。
保持r'...'
find = r'\]\n'
replace = r']'
text = re.sub(find, replace, text)
或去
find = '\\]\\n'
replace = ']'
text = re.sub(find, replace, text)
簡短的回答:你應該用字符串保持r
在一起。
r
前綴是字符串語法的一部分。使用r
時,Python不會在引號內解釋反斜槓序列,如\n
,\t
等。如果沒有r
,則必須輸入每個反斜槓兩次以將其傳遞到re.sub
。
r'\]\n'
和
'\\]\\n'
都寫相同的字符串兩種方式。
好吧,我認爲這是'特定'。 – Qiao
@喬:使用'r'''原始文字可以更容易地指定正則表達式。這不是要求使用它們。 –
@喬:不。請參閱我已添加到我的答案中的文檔鏈接。 – NPE