简体   繁体   English

用re.sub删除换行符

[英]Remove newline with re.sub

Why is the result 'bc' and not 'abc'?: 为什么结果是“ bc”而不是“ abc” ?:

>>> import re
>>> re.sub('-\n([a-z])', '','-\nabc',re.M)
'bc'

re.sub replace matched pattern with replacement string. re.sub替换字符串替换匹配的模式。 ([az]) here is also matched, so it gets removed. ([az])也匹配,因此将其删除。 To avoid this, you can use look ahead syntax: 为避免这种情况,可以使用前瞻语法:

import re
re.sub('-\n(?=[a-z])', '','-\nabc',re.M)
# 'abc'

You can just specify the string to be replaced: 您可以只指定要替换的字符串:

re.sub('-\\n', '','-\\nabc')

will return just the abc 将仅返回abc

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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