0

I have a string variable containing .10 I would like to format it to print out 0.10. Is there a way I could somehow pass the desired string format to the variable and the variable formats accordingly.

ex.

.10 becomes 0.10 (formatting 0.00)
.10 becomes 0.100 (formatting 0.000)
50.10 becomes 50.1 (formatting 0.0)

the version of python that I use is 2.4.

2 Answers 2

2

If you want the formatting to be variable:

>>> '%.*f' % (1,.1)
'0.1'
>>> '%.*f' % (2,.1)
'0.10'
>>> '%.*f' % (3,.1)
'0.100'
>>> '%*.*f' % (5,3,.1)
'0.100'
>>> '%*.*f' % (5,2,.1)
' 0.10'
>>> '%*.*f' % (5,1,.1)
'  0.1'

Reference: Python 2.4.4, §2.3.6.2 String Formatting Operations

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

Comments

1
>>> '%.2f' % (float('.10'),)
'0.10'

2 Comments

For python 2.4, this is correct, but I don't think you need to put it in a tuple... Just for future users, if you are using 2.6 or later, it is better to use str.format -- as I believe this style of formatting is now deprecated.
You don't need to put non-tuple values in a tuple; this is simply force of habit for me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.