[英]Python re.sub does not replace newline
I have some text like this:我有一些这样的文字:
<Row 1 Having A Text>
<Row 2 Having B Text>
<Row 3 Having C Text>
I am trying to remove entirely and shift up.我正在尝试完全移除并向上移动。
I have been trying to use this:我一直在尝试使用这个:
for line in fileinput.input(new_name, inplace=True):
print (re.sub(r'<Row 2.*[\r\n]*', '', line.strip()))
However, this just results in the following:但是,这只会导致以下结果:
<Row 1 Having A Text>
<Row 3 Having C Text>
And Row 3 does not move up.并且第 3 行没有向上移动。 What am I missing here?
我在这里错过了什么?
Your problem is that even though your regex matches and replaces the contents of line
with an empty string ( ''
), print('')
will output a blank line.您的问题是,即使您的正则表达式匹配并用空字符串 (
''
) 替换line
的内容, print('')
也会 output 为空行。 Instead of printing every line, print just the lines that don't start with <Row 2
不是打印每一行,而是只打印不以
<Row 2
开头的行
for line in fileinput.input(new_name, inplace=True):
if not line.strip().startswith('<Row 2'):
print(line)
print()
outputs the LF even if the content is empty, so you replace 'Row 2' with an empty string, but since you still use print
, you get an empty line on output.即使内容为空,
print()
也会输出 LF,因此您将“第 2 行”替换为空字符串,但由于您仍在使用print
,因此在 output 上会得到一个空行。
You may check for an empty line:您可以检查空行:
for line in fileinput.input(new_name, inplace=True):
output = re.sub(r'<Row 2.*[\r\n]*', '', line.strip())
if len(output) :
print(output)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.