Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove some dots from a string in python

Tags:

python-3.x

I'm extracting an int from a table but amazingly comes as a string with multiple full stops. This is what I get:

p = '23.4565.90'

I would like to remove the last dots but retain the first one when converting to an in. If i do

print (p.replace('.',''))

all dot are removed How can I do this.

N/B Tried a long way of doing this

p = '88.909.90000.0'
pp = p.replace('.','')
ppp = list(''.join(pp))
ppp.insert(2, '.')
print (''.join(ppp))

BUT discovered that some figures come as e.g. 170.53609.45 and with this example, I'll end up with 17.05360945 instead of 170.5360945

like image 894
lobjc Avatar asked Jun 17 '26 05:06

lobjc


2 Answers

Here is a solution:

p = '23.4565.90'

def rreplace(string: str, find: str, replace: str, n_occurences: int) -> str:
    """
    Given a `string`, `find` and `replace` the first `n_occurences`
    found from the right of the string.
    """
    temp = string.rsplit(find, n_occurences)
    return replace.join(temp)

d = rreplace(string=p, find='.', replace='', n_occurences=p.count('.') - 1)

print(d)

>>> 23.456590

Credit to How to replace all occurences except the first one?.

like image 76
Error - Syntactical Remorse Avatar answered Jun 18 '26 18:06

Error - Syntactical Remorse


What about str.partition?

p = '23.4565.90'
a, b, c = p.partition('.')
print(a + b + c.replace('.', ''))

This would print: 23.456590

EDIT: the method is partition not separate

like image 43
thedadams Avatar answered Jun 18 '26 17:06

thedadams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!