简体   繁体   English

格式化字符串、小数和逗号问题

[英]Formatted strings, decimals and commas question

I have a.txt file that I read in and wish to create formatted strings using these values.我有一个 .txt 文件,我读了它并希望使用这些值创建格式化字符串。 Columns 3 and 4 need decimals and the last column needs a percent sign and 2 decimal places.第 3 列和第 4 列需要小数,最后一列需要百分号和 2 位小数。 The formatted string will say something like "The overall attendance at Bulls was 894659, average attendance was 21,820 and the capacity was 104.30%'格式化的字符串将显示类似“公牛队的总上座率为 894659,平均上座率为 21,820,容量为 104.30%”

the shortened.txt file has these lines: shortened.txt 文件包含以下几行:

1   Bulls   894659  21820   104.3
2   Cavaliers   843042  20562   100
3   Mavericks   825901  20143   104.9
4   Raptors 812863  19825   100.1
5   NY_Knicks   812292  19812   100

So far my code looks like this and its mostly working, minus the commas and decimal places.到目前为止,我的代码看起来像这样,并且它大部分工作,减去逗号和小数位。

file_1 = open ('basketball.txt', 'r')
count = 0

list_1 = [ ]
for line in file_1:
    count += 1
    textline = line.strip()
    items = textline.split()
    list_1.append(items)

print('Number of teams: ', count)
for line in list_1:
    print ('Line: ', line)

file_1.close()

for line in list_1: #iterate over the lines of the file and print the lines with formatted strings
    a, b, c, d, e = line
    print (f'The overall attendance at the {b} game was {c}, average attendance was {d}, and the capacity was {e}%.')

Any help with how to format the code to show the numbers with commas (21820 ->21,828) and last column with 2 decimals and a percent sign (104.3 -> 104.30%) is greatly appreciated.非常感谢任何有关如何格式化代码以显示带有逗号 (21820 ->21,828) 的数字和带有 2 位小数和百分号 (104.3 -> 104.30%) 的最后一列的帮助。

You've got some options for how to tackle this.对于如何解决这个问题,您有一些选择。

Option 1: Using f strings ( Python 3 only )选项 1:使用 f 字符串(仅限 Python 3

Since your provided code already uses f strings, this solution should work for you.由于您提供的代码已经使用 f 字符串,因此此解决方案应该适合您。 For others reading here, this will only work if you are using Python 3.对于阅读此处的其他人,这仅在您使用 Python 3 时有效。

You can do string formatting within f strings, signified by putting a colon : after the variable name within the curly brackets {} , after which you can use all of the usual python string formatting options .您可以在 f 字符串中进行字符串格式化,通过在大括号{}内的变量名称后放置一个冒号:表示,之后您可以使用所有常用的python 字符串格式化选项

Thus, you could just change one of your lines of code to get this done.因此,您只需更改其中一行代码即可完成此操作。 Your print line would look like:您的打印行看起来像:

print(f'The overall attendance at the {b} game was {int(c):,}, average attendance was {int(d):,}, and the capacity was {float(e):.2f}%.')

The variables are getting interpreted as:变量被解释为:

  • The {b} just prints the string b . {b}只打印字符串b
  • The {int(c):,} and {int(d):,} print the integer versions of c and d , respectively, with commas (indicated by the :, ). {int(c):,}{int(d):,}分别打印cd的 integer 版本,使用逗号(由:,表示)。
  • The {float(e):.2f} prints the float version of e with two decimal places (indicated by the :.2f ). {float(e):.2f}打印带有两位小数的e的浮点数版本(由:.2f表示)。

Option 2: Using string.format()选项 2:使用string.format()

For others here who are looking for a Python 2 friendly solution, you can change the print line to the following:对于在这里寻找 Python 2 友好解决方案的其他人,您可以将打印行更改为以下内容:

print("The overall attendance at the {} game was {:,}, average attendance was {:,}, and the capacity was {:.2f}%.".format(b, int(c), int(d), float(e)))

Note that both options use the same formatting syntax, just the f string option has the benefit of having you write your variable name right where it will appear in the resulting printed string.请注意,这两个选项使用相同的格式化语法,只是 f 字符串选项的好处是让您将变量名写在它出现在结果打印字符串中的正确位置。

This is how I ended up doing it, very similar to the response from Bibit.这就是我最终这样做的方式,与 Bibit 的回应非常相似。

file_1 = open ('something.txt', 'r')

count = 0

list_1 = [ ]
for line in file_1:

    count += 1
    textline = line.strip()  
    items = textline.split()
    items[2] = int(items[2])
    items[3] = int(items[3])
    items[4] = float(items[4])

    list_1.append(items)

print('Number of teams/rows: ', count)

for line in list_1:
    print ('Line: ', line)

file_1.close()

for line in list_1:
   print ('The overall attendance at the {:s} games was {:,}, average attendance was {:,}, and the capacity was {:.2f}%.'.format(line[1], line[2], line[3], line[4]))

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

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