从列表中删除\ n时出现问题

时间:2015-07-14 00:27:47

标签: python python-3.x

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

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']

2 个答案:

答案 0 :(得分:2)

你实际上并没有修改numList。你可以这样做一行列表理解:

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

答案 1 :(得分:0)

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