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

本文详细介绍了如何使用Python的字符串格式化方法和列表连接方法来处理CSV文件,通过实例展示了如何创建并写入包含奥运选手信息的数据行。
1081

被折叠的 条评论
为什么被折叠?



