【问题标题】:Problems removing \n from a list [duplicate]从列表中删除 \n 时出现问题 [重复]
【发布时间】:2015-07-14 00:27:47
【问题描述】:

我查找了各种有意义的解决方案,并尝试在我的代码中实现它们。当我打印出列表时,我仍然收到带有换行符的数字。这是我的代码:

infile = open(r"C:\Users\rr205951\Documents\nums.txt", "r")
    numList = infile.readlines()
    print("Before: ", numList)

    for num in numList:
        num = num.rstrip('\n')

    print("After: ", numList)

当我运行上面的代码时,它仍然返回以下内容:

Before:  ['15\n', '4\n', '3\n', '25\n', '2000\n', '328\n', '20\n', '9\n', '18\n', '4333\n']
After:  ['15\n', '4\n', '3\n', '25\n', '2000\n', '328\n', '20\n', '9\n', '18\n', '4333\n']

【问题讨论】:

  • numList = [i.strip() for i in infile.readlines()]
  • 查看this 答案。它涵盖了 5 种以上的工作方式

标签: python python-3.x


【解决方案1】:

您实际上并没有修改 numList。您可以像这样进行单行列表理解:

#read your lines as you did, but add the following after. numList = [num.strip() for num in numList]

【讨论】:

  • 这很好,因为它解释了为什么 OP 代码不能按预期工作。
【解决方案2】:

numList = map(lambda s: s.strip(), numList)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    • 2021-12-15
    • 2013-04-01
    • 2011-10-31
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多