Help with decimal places and commas in formatted string

Good afternoon everyone,

I just started learning Python for a class and I am a little stuck on something. I have searched the forum, found a few answers and I am close to getting it but the question is asking for commas and decimals in some of the columns.

I have a .txt file that I read in and make a formatted string with the following code:

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:
  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}%.')

the first 5 lines of the output look like this:
The overall attendance at the Bulls game was 894659, average attendance was 21820, and the capacity was 104.3%.
The overall attendance at the Cavaliers game was 843042, average attendance was 20562, and the capacity was 100%.
The overall attendance at the Mavericks game was 825901, average attendance was 20143, and the capacity was 104.9%.
The overall attendance at the Raptors game was 812863, average attendance was 19825, and the capacity was 100.1%.
The overall attendance at the NY_Knicks game was 812292, average attendance was 19812, and the capacity was 100%.

This works and is very close to what is being asked but I still need 2 decimal places for the percent and commas in the attendance. Is there a way to do this with how I currently have the code? Any help is greatly appreciated!!

I guess you could use .format for strings for some of that.
link to learnpython.com stuff
You’d use {:,} for commas for the thousands.
and {:2f} to get a string version of the float rounded to 2 places.

num = 2 ** 15 #32768 proportion = 0.125 # 1/8 percentage = proportion * 100 str1 = "2^15 is {:,}".format(num) str2 = "{:.2f}% is 1/8 as a percentage".format(percentage) print(str1) print(str2)
1 Like

Thank you very much for the response!! I ended up stepping away and figuring it out when I came back. This is how I did it:

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]))