lucky1928
lucky1928

Reputation: 8935

remove last character with sub regex call

Try to remove the last "," of each line but current logic only remove the last one:

import re

x = """
A,B,C,
1,2,3,
4,5,6,
7,8,9,
"""
x = re.sub(",$","",x,re.MULTILINE)
print(x)

Output:

A,B,C,
1,2,3,
4,5,6,
7,8,9

expected output:

A,B,C
1,2,3
4,5,6
7,8,9

Upvotes: 1

Views: 56

Answers (2)

Hannon qaoud
Hannon qaoud

Reputation: 958

this should do it:

import re

x = """
A,B,C,
1,2,3,
4,5,6,
7,8,9,
"""
# regix to remove all commas at the end of each line
x = re.sub(r',$', '', x, flags=re.M)
# '$', means the end of the line
# '', means replace with nothing
# x, os the string to be searched
# flags=re.M, means to search the whole string, not just the first line
# flags=re.MULTILINE does the same job
print(x)

output->

A,B,C
1,2,3
4,5,6
7,8,9

Upvotes: 2

vks
vks

Reputation: 67998

re.sub(regex, subst, test_str, 0, re.MULTILINE)

flag is 5th argument.

Upvotes: 4

Related Questions