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()
stripreturns 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
readthe whole thing then
withstatement saves you from having to call
stripaccepts multiple characters, so you don't need to call it three times.
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