0

I have looked up various solutions that make sense, and tried to implement them in my code. When I print out the list I'm still receiving the number with a newline character. Here is my code:

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)

When I run the above code it still returns this following:

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']
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
flybonzai
  • 3,763
  • 11
  • 38
  • 72

2 Answers2

2

You're not actually modifying numList. You could do a one-liner list comprehension like so:

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

blasko
  • 690
  • 4
  • 8
0

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

erip
  • 16,374
  • 11
  • 66
  • 121