如何仅输出列表数据中的字符串?

2024-09-30 03:25:56 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: 文件代码intxtinputfile2filebob
3条回答

一个选项是使用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))

那怎么办

for line1 in bob:
    teamname.append(line1.strip()) # .strip() removes the \n

print (', '.join(teamname))

.join()进行最终格式化


更新。我现在认为一个更具python主义(优雅)的答案是:

file2 = input("Enter the team-names file: ") ## E.g. teamNames.txt

with open(file2) as f:
    teamname = [line.strip() for line in f]

print (', '.join(teamname))

with语句确保在块完成时关闭文件。它现在不再执行for循环,而是使用list comprehension,这是一种通过转换另一个列表(或从iterable object,如file)中的元素来创建列表的酷方法

join方法工作得很好,但是您也可以尝试使用for循环

for name in teamname: # takes each entry separately 
    print name

相关问题 更多 >

    热门问题