1

Suppose i have numeric string. I would like to remove all the trailing zeros and also the decimal point if necessary. For example -

'0.5' -> '.5'
'0005.00' -> '5'

I used this method :

s.strip("0") # where 's' contains the numeric string.

But for the 0005.00, it returns 5., so how would i remove the decimal point if necessary.

2 Answers 2

2

To achieve this you could write a little function

def dostuff(s):
    s = s.strip('0')
    if len(s) > 0 and s[-1] == '.':
        s = s[:-1]
    return s

This strips all the 0s and if a . was found and it was at the end of the string (meaning its the decimal point and nothing follows it) it will strip that too using [s:-1] (this strips the last character).

s[-1] gets the last character of the string. With this we can check if . is the last character.

This may be achieved with less code using a regex, but I think this is easier to follow

Demo

>>> print dostuff('5.0')
5
>>> print dostuff('005.00')
5
>>> print dostuff('.500')
.5
>>> print dostuff('.580')
.58
>>> print dostuff('5.80')
5.8
Sign up to request clarification or add additional context in comments.

1 Comment

@DSM nice catch, I believe this should fix it
0

try this it worked with me to remove all zeros from my numbers, I would that help you.

word = str(num).split('0') #to convert numbers to list without zeros
word = ''.join(word)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.