【问题标题】:How to output only the string in list data?如何仅输出列表数据中的字符串?
【发布时间】:2018-05-06 21:30:00
【问题描述】:

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

【问题讨论】:

  • 当您将line1 附加到teamname 时,只需在strip 之前使用line1 使用teamname.append(line1.strip())。在 print 中,使用 print(“, “.join(teamname)) 将您的列表转换为字符串

标签: python string list split append


【解决方案1】:

怎么样

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

print (', '.join(teamname))

.join() 进行最终格式化。


更新。我现在认为一个更蟒蛇(和优雅)的答案是:

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)中的元素来创建列表。

【讨论】:

  • 非常感谢!我知道这个问题很简单,我使用了 split,但它像 teamname = teamname.split() 那样给出了错误。
【解决方案2】:

join 方法效果很好,但您也可以尝试使用 for 循环。

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

【讨论】:

    【解决方案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))
    

    【讨论】:

    • 非常感谢!我从未考虑过 replace() 函数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多