简体   繁体   中英

Python string format() function using zero in the syntax to reference dictionary

I am reading the Python documentation on fancier output formatting and they have example code which is confusing. In the following code:

table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}

print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; Dcab: {0[Dcab]:d}'.format(table))

Jack: 4098; Sjoerd: 4127; Dcab: 8637678

What does the 0 refer to in {0[Jack]:d} and {0[Sjoerd]:d} . The tutorial's explanation omits any hint about the function of those zeros. This video tutorial about formatting strings uses the same syntax without explaining it clearly too!

If I put a 1 in the place of 0 I get the error:

IndexError: tuple index out of range

What on Earth has the tuple have to do with it?

Taken from the Documentation:

If you have a really long format string that you don't want to split up, it would be nice if you could reference the variables to be formatted by name instead of by position. This can be done by simply passing the dict and using square brackets '[]' to access the keys

You can just use:

table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
print('Jack: {Jack}; Sjoerd: {Sjoerd}; Dcab: {Dcab}'.format(**table))

The 0 is the index of the format argument, ie table in this case.

It doesn't work with 1 because there's only one argument, that's what "tuple index out of range" is saying.

The documentation does mention this here :

A number in the brackets can be used to refer to the position of the object passed into the str.format() method.

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