6

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

lobjc
  • 2,751
  • 5
  • 24
  • 30

4 Answers4

7

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?.

5

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

thedadams
  • 106
  • 4
0

This isnt the best way in doing it especially if your not getting similar values but if you do some sort of loop to check how many values there are then do this it should work. but if you only have three dots in the string try this:

p = '88.909.90000.0'
p = p.split('.')
p = p[0] + '.' + p[1] + p[2]

then if you want it as a number do this p = float(p)

Dextron
  • 598
  • 7
  • 24
0
def add_dots(to_add):
    res=""
    for letter in to_add:
        res= res + letter + "."
        print{:-1}res)
    
def remove_dots(to_remove): 
    print (to_remove):
    
add_dots("test")    
remove_dots("t.e.s.t.")
RiveN
  • 2,595
  • 11
  • 13
  • 26
  • While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Yunnosch Sep 11 '22 at 01:16