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

标签 python string list split append

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

相关文章:

python - 如何在条件检查时从现有数据帧复制数据帧中的选定行? [Python]

python - 如果条件在 python 中的循环内

python - Pyramid 可以将默认的request.charset从utf-8更改为gbk吗?

android - Unknown class R.string ...提取字符串资源时

python - 值错误: malformed node or string error when parsing lists from a text file

python - 根据列表项的索引模进行不同的操作

python - 如何让 python XOR 解密多行字符串?

c - 在 C 中从文件中读取长行时处理内存

c - 为什么 strlen 在没有 '\0' 的情况下工作正常?

python - 如何以 "pretty"格式打印二维数组?