我的文件读取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))

10-06 08:49