Mozbi
Mozbi

Reputation: 1479

Python regular expression remove period from number at end of sentence

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

Answers (4)

Ashalynd
Ashalynd

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

Nir Alfasi
Nir Alfasi

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

user557597
user557597

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

GVH
GVH

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

Related Questions