简体   繁体   English

python字符串格式的意外打印输出

[英]Unexpected print output for python string formatting

I want to print some values using str.format .我想使用str.format打印一些值。 However, I am getting the first value repeated, which I do not understand.但是,我得到了重复的第一个值,我不明白。 Any help will be appreciated.任何帮助将不胜感激。

for tel in ['T1', 'T2', 'T3', 'T4']:
    print(tel+':{0:.2f}, {0:.2f}, {0:.2f}'.format(0.56, 0.12, 0.25))

That's because of the zero in {0:.2f} which means 'argument at index 0', so you call always the same, just remove it, and it'll use arguments in their order这是因为{0:.2f}中的零表示“索引 0 处的参数”,因此您始终调用相同的方法,只需将其删除,它将按顺序使用参数

for tel in ['T1', 'T2', 'T3', 'T4']:
    print(tel + ':{:.2f}, {:.2f}, {:.2f}'.format(0.56, 0.12, 0.25))

The first entry in curly braces is the index of the list you reference in the format statement.花括号中的第一个条目是您在格式语句中引用的列表的索引。 So you always take the first entry by saying {0:x}.因此,您总是通过说 {0:x} 来获取第一个条目。 What you need to do is:你需要做的是:

print(tel+':{0:.2f}, {1:.2f}, {2:.2f}'.format(0.56, 0.12, 0.25))

or leave it empty like {:x}.或者像 {:x} 一样留空。

The number before : is the index of the argument in format() so you are selecting the first argument in all three places.前面的数字:在参数的索引format()所以你选择在这三个地方的第一个参数。 You should use {:.2f} instead of {0:.2f} .您应该使用{:.2f}而不是{0:.2f}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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