curioustea
curioustea

Reputation: 13

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. What am I missing here?

Upvotes: 1

Views: 1111

Answers (2)

Nick
Nick

Reputation: 147146

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. Instead of printing every line, print just the lines that don't start with <Row 2

for line in fileinput.input(new_name, inplace=True): 
    if not line.strip().startswith('<Row 2'):
        print(line)

Upvotes: 3

lenik
lenik

Reputation: 23498

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.

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)

Upvotes: 0

Related Questions