[Tutor] Some questions about my yen-USD.py

Andrei project5 at redrival.net
Fri Sep 8 08:57:01 CEST 2006


Dick Moores <rdm <at> rcblue.com> writes:

> So now that I know better, I'm trying to write the beginnings of a 
> general setPrecision() function using format strings. However, it 
> appears that a variable cannot be used instead of the ".2" in
> 
> "%.2f" % 2.234234
<snip>
> How to do this?

You could use simple string concatenation:

>>> "%." + str(2) + 'f'
'%.2f'
>>> "%." + str(4) + 'f'
'%.4f'

Or use format strings to create other format strings, by escaping the '%' with
'%%'. E.g.:

>>> "%%.%df" % 2 # the '%%' will be changed to '%' in the result
'%.2f'
>>> "%%.%df" % 4
'%.4f'
>>> s1 = "%%.%df" % 2
>>> print s1, s1 % 3.41234
'%.2f', '3.41'
>>> s2 = "%%.%df" % 4
>>> print s2, s2 % 3.41234
'%.4f', '3.4123'
>>> ("%%.%df" % 2) % 3.23423 
'3.23'

Yours,

Andrei



More information about the Tutor mailing list