2012-11-26 100 views
0

我需要做這個變量:使用 「R」 在應用re.sub

text = re.sub(r'\]\n', r']', text) 

但隨着findreplace變量:

find = '\]\n' 
replace = ']' 
text = re.sub(find, replace, text) 

我應該在哪裏把r(原料)?它不是一個字符串。

回答

2

r''的是string literal syntax的一部分:

find = r'\]\n' 
replace = r']' 
text = re.sub(find, replace, text) 

的語法是決不特定於re模塊。但是,指定正則表達式是原始字符串的主要用例之一。

+0

好吧,我認爲這是'特定'。 – Qiao

+0

@喬:使用'r'''原始文字可以更容易地指定正則表達式。這不是要求使用它們。 –

+0

@喬:不。請參閱我已添加到我的答案中的文檔鏈接。 – NPE

1

保持r'...'

find = r'\]\n' 
replace = r']' 
text = re.sub(find, replace, text) 

或去

find = '\\]\\n' 
replace = ']' 
text = re.sub(find, replace, text) 
1

簡短的回答:你應該用字符串保持r在一起。

r前綴是字符串語法的一部分。使用r時,Python不會在引號內解釋反斜槓序列,如\n,\t等。如果沒有r,則必須輸入每個反斜槓兩次以將其傳遞到re.sub

r'\]\n' 

'\\]\\n' 

都寫相同的字符串兩種方式。