【问题标题】:Remove "\n" from a list of numbers从数字列表中删除“\n”
【发布时间】:2014-09-25 18:10:25
【问题描述】:

我创建了三个文本文件,每个文件都有 10 个用逗号分隔的随机数。然后我有一个 python 程序,它从用户那里接受一个文本文件的名称,将文本文件中的数字读入一个列表,然后对原始列表和排序后的列表进行排序和打印。

prompt = raw_input("Enter the name of the text file you want to open: ")
fileopen = open(prompt)
for line in fileopen:
numbers = line.split(",")
sortednumbers = sorted(numbers)
print numbers
print sortednumbers

但是,打印的结果列表始终只包含一个在数字末尾附加“\n”的值(例如 99\n)。我注意到它总是文本文件中的最后一个数字。我怎样才能让它只显示文本文件中没有“\n”的数字?

【问题讨论】:

标签: python list sorting text formatting


【解决方案1】:

谢谢达斯比斯!这有效:

使用strip或rstrip,如numbers = line.strip().split(',')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-03
    • 1970-01-01
    • 2017-09-04
    • 2012-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多