gpt4 book ai didi

python - 如何只输出列表数据中的字符串?

转载 作者:太空宇宙 更新时间:2023-11-03 14:28:52 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com