Home > Software engineering >  Is there any python keyword for replacing last decimal point from a number string
Is there any python keyword for replacing last decimal point from a number string

Time:10-26

I am trying to replace the decimal point with null except last decimal eg:

number="123.34.56.04"

I need to delete 123.34.56 and need to get the final answer as .04 anyone, please help me to out of this. Thanks in advance

CodePudding user response:

Try splitting the number using the dot as a separator and then get the last value. The number variable needs to be a string:

number = "123.34.56.04"
list1 = number.split(".")
last_number = list1[-1] # to get the last value

CodePudding user response:

You can use .rpartition('.') to split the string by the right most '.':

>>> number="123.34.56.04"
>>> number.rpartition('.')
('123.34.56', '.', '04')

Then use .join to reform the number:

>>> ''.join(number.rpartition('.')[1:])
'.04'

This works as expected even if there is no '.':

>>> ''.join('1234'.rpartition('.')[1:])
'1234'
  • Related