Reputation: 1479
If I have a string as such: "I like the numbers 3.142 and 2."
And I want to remove the period after 2 but not the one in 3.142, how should I perform this? Basically, how do I check if a number followed by a period doesn't have numbers following the period and how do I remove that period? Thanks.
Upvotes: 1
Views: 8182
Reputation: 12563
>>> import re
>>> s = "I. always. like the numbers 3.142, 5., 6.12 and 2. Lalala."
>>> re.sub('((\d+)[\.])(?!([\d]+))','\g<2>',s)
'I. always. like the numbers 3.142, 5, 6.12 and 2 Lalala.'
Upvotes: 2
Reputation: 53525
Wrikken wrote a good solution in the comments above, it removes the dot only when it comes after a digit and is not followed by a digit:
import re
sen = "I like the numbers 3.142 and 2. and lalala."
p = re.compile("(?<=\d)(\.)(?!\d)")
new_sen = p.sub("",sen)
print (new_sen) #prints: I like the numbers 3.142 and 2 and lalala.
Upvotes: 2
Reputation:
In multi-line mode, this should work. Use in global context.
This will process multi-lined strings in one go.
It finds the last period, with optional non-newline whitespace to the end of line
checked with a lookahead assertion.
Find:
\.(?=[^\S\r\n]*$)
Replace: ""
Upvotes: 0
Reputation: 414
If you just want to delete a period at the end of a line:
>>> import re
>>> sentence = "I like the numbers 3.142 and 2."
>>> re.sub(r'\.+$', '', sentence)
'I like the numbers 3.142 and 2'
If you want to delete any decimals not followed by a digit, use negative lookahead:
>>> re.sub(r'\.(?!\d)', '', sentence)
'I like the numbers 3.142 and 2'
Upvotes: 1