简体   繁体   中英

str.format() error for printing floats in Python 2.6

I'm trying to print some floats using Python's str.format(). Here's a sample code

table = {'pi':3.1415926}
for variable, value in table.items():
    print '{0:10} ==> {0:.2f}'.format(variable, value)

I get the following error when I do this

ValueError: Unknown format code 'f' for object of type 'str'

I don't understand why Python thinks 3.1415926 is a string.

Thanks.

You have the positions backwards:

table = {'pi':3.1415926}
for variable, value in table.items():
    print '{0} ==> {1:.2f}'.format(variable, value)

pi ==> 3.14

Or simply remove the variable unless you actually want to print pi and iterate over the values:

for  value in table.values():
    print '{0} ==> {0:.2f}'.format(value)

3.1415926 ==> 3.14

You can also use the dict with **:

table = {'pi':3.1415926}

print '{pi} ==> {pi:.2f}'.format(**table)

When you write {0} it refers to the first argument of the format function. You need to change it to 1.

table = {'pi':3.1415926}
for variable, value in table.items():
    print '{0:10} ==> {1:.2f}'.format(variable, value)

Edit Following @AshwiniChaudhary's comment - in Python 2.7 you don't even need to specify the numbers and it will automatically use them in order

table = {'pi':3.1415926}
for variable, value in table.items():
    print '{:10} ==> {:.2f}'.format(variable, value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM