我的文件读取teamNames.txt文件,该文件为:
Collingwood
Essendon
Hawthorn
Richmond
代码:
file2 = input("Enter the team-names file: ") ## E.g. teamNames.txt
bob = open(file2)
teamname = []
for line1 in bob: ##loop statement until no more line in file
teamname.append(line1)
print(teamname)
输出为:
['Collingwood\n', 'Essendon\n', 'Hawthorn\n', 'Richmond\n']
我想使其输出为:
Collingwood, Essendon, Hawthorn, Richmond
一个选项是使用
replace()
函数。我已经修改了您的代码以包含此函数将为您提供以下输出:
然后可以修改
teamname
以获得请求的输出:那怎么办
.join()
进行最终格式化更新。我现在认为一个更具python主义(优雅)的答案是:
with
语句确保在块完成时关闭文件。它现在不再执行for
循环,而是使用list comprehension,这是一种通过转换另一个列表(或从iterable object,如file
)中的元素来创建列表的酷方法join方法工作得很好,但是您也可以尝试使用for循环
相关问题 更多 >
编程相关推荐