简体   繁体   中英

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)

I'm on Python 2.7.15. The output is PO 00000 Frm 00001 Fmt 0624 Sfmt 0634 E:\\CR\\FM\\A07JN6.000 S07JNPT1 . Why doesn't the output become " " ?

Looks like you need re.escape

Ex:

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)

Note: You can also use str.replace for this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM