How to use strip () in python

advertisements

I have a text file test.txt which has in it 'a 2hello 3fox 2hen 1dog'.
I want to read the file and then add all the items into a list, then strip the integers so it will result in the list looking like this 'a hello fox hen dog'

I tried this but my code is not working. The result is ['a 2hello 3foz 2hen 1dog']. thanks

newList = []
filename = input("Enter a file to read: ")
openfile = open(filename,'r')

for word in openfile:
    newList.append(word)

for item in newList:
    item.strip("1")
    item.strip("2")
    item.strip("3")

print(newList)
openfile.close()


Pointers:

  • strip returns a new string, so you need to assign that to something. (better yet, just use a list comprehension)
  • Iterating over a file object gives you lines, not words;
  • so instead you can read the whole thing then split on spaces.
  • The with statement saves you from having to call close manually.
  • strip accepts multiple characters, so you don't need to call it three times.

Code:

filename = input("Enter a file to read: ")
with open(filename, 'r') as openfile:
    new_list = [word.strip('123') for word in openfile.read().split()]
print(new_list)

This will give you a list that looks like ['a', 'hello', 'fox', 'hen', 'dog']
If you want to turn it back into a string, you can use ' '.join(new_list)