1

I'm trying to use a string of a decimal, but I am getting an unwanted "0.". For example:

age = .01
print 'test%s'%(age)
print 'test' + str(age)

These both return 'test0.01', but I want 'test.01'. I know there is a simple solution. Any thoughts?

3 Answers 3

6
age = .01
print 'test' + str(age).lstrip('0')

Works for age > 1.0 as well.

Sign up to request clarification or add additional context in comments.

2 Comments

The question doesn't actually say age is always positive, so it might matter that it doesn't work for -1 < age < 0. Then again it may not.
That would give strange answer if age = 0
2
age = .01
print 'test%s' % str(age)[1:] if 0<age<1 else str(age)

3 Comments

Exactly what I was looking for (with the conditional statement), though you do have a typo with a single quote instead of a paren around age. Thanks!
Fails for x such that -1 < x < 0.
it is not specified what he want in those cases -.01 doesn't seems be a sensible answer in my opinion
0
age = .01
print 'test' + (str(age)[1:] if 0 < age < 1 else str(age))

6 Comments

Note: fails for x outside of 0 < x < 1. Safe: replace "0" with "" if followed by "." and not preceded by a digit (easy with regexp: lookahead and negative lookbehind). Or just use this, for numbers between 0 and 1, and a similar action for numbers between -1 and 0.
That will break for ages > 1.
No, but presumably he also wants an answer that works for more than just the exact number given (for example, the lstrip()-based one). If you only want an answer that works for the example given, "print 'test .01'" will do...
Sure, I'm just saying that he said his problem was an unwanted '0'. I mean this code doesn't work if age = five either. I'm not claiming to have put forward the greatest python code ever written, just trying to give him something to work with.
@BenH: Sorry - to clarify, I commented at the time when you did not have the if yet. This fixes it for positive numbers; -1 < x < 0 still won't work (although the solution is simple and analogous, and just an additional if away).
|

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.