First, using .format() makes it really clear what we’re doing when we create the variable row_string. We are making a comma separated set of values; the {} curly braces indicated where to substitute in the actual values. The equivalent string concatenation would be very hard to read. An alternative, also clear way to do it would be with the .join method: row_string = ‘,’.join(olympian[0], olympian[1], olympian[2]).
olympians = [("John Aalberg", 31, "Cross Country Skiing, 15KM"),
("Minna Maarit Aalto", 30, "Sailing"),
("Win Valdemar Aaltonen", 54, "Art Competitions"),
("Wakako Abe", 18, "Cycling")]
outfile = open("reduced_olympics2.csv", "w")
# output the header row
outfile.write('"Name","Age","Sport"')
outfile.write('\n')
# output each of the rows:
for olympian in olympians:
row_string = '"{}", "{}", "{}"'.format(olympian[0], olympian[1], olympian[2])
#row_string=','.join([olympian[0], str(olympian[1]), olympian[2]]) 可以把元素放进列表,用join连接起来。要将Int类型转化为str
outfile.write(row_string)
outfile.write('\n')
outfile.close()