Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use strip() in python

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()
like image 218
nonen Avatar asked Jun 03 '26 18:06

nonen


1 Answers

from python Doc

str.strip([chars])
Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:

Strip wont modify the string, returns a copy of the string after removing the characters mentioned.

>>> text = '132abcd13232111'
>>> text.strip('123')
'abcd'
>>> text
'132abcd13232111'

You can try:

out_put = []
for item in newList:
    out_put.append(item.strip("123"))

If you want to remove all 123 then use regular expression re.sub

import re
newList = [re.sub('[123]', '', word) for word in openfile]

Note: This will remove all 123 from the each line

like image 107
Praveen Avatar answered Jun 06 '26 07:06

Praveen