![](/img/trans.png)
[英]Why does re.sub in Python not work correctly on this test case?
[英]Why doesn't re.sub work in this python2 case?
import re
text = "PO 00000 Frm 00001 Fmt 0624 Sfmt 0634 E:\CR\FM\A07JN6.000 S07JNPT1"
text = re.sub(text, " ", text)
print(text)
我使用的是Python 2.7.15。 輸出為PO 00000 Frm 00001 Fmt 0624 Sfmt 0634 E:\\CR\\FM\\A07JN6.000 S07JNPT1
。 為什么輸出不變成" "
?
看起來您需要re.escape
例如:
import re
text = "PO 00000 Frm 00001 Fmt 0624 Sfmt 0634 E:\CR\FM\A07JN6.000 S07JNPT1"
text = re.sub(re.escape(text), " ", text)
print(text)
注意:在這種情況下,您也可以使用str.replace
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.