我的文件读取 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()
函数。我已修改您的代码以包含此功能。
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.replace("\n",""))
print(teamname)
会给你输出:
['Collingwood', 'Essendon', 'Hawthorn', 'Richmond']
然后您可以修改teamname
以获得您请求的输出:
print(", ".join(teamname))
关于python - 如何只输出列表数据中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47446626/