Search code examples
pythonstrip

Removing numbers.


Im trying to remove numbers from a print statement, but when i do try, it doesn't. It actually adds extra lines that are unwanted.

p=open('test1.txt','r')
t=open('outChanger.txt','w')

counter=0
for l in p:
counter+=1
if counter%3==0:
    print((l.swapcase()*2),l.strip('2'))

t.close()
p.close()

I want it to look like this, but without the 2's.

tHE ANTS GO MARCHING 2 BY 2,

tHE ANTS GO MARCHING 2 BY 2,

(It adds this with the .strip.) The ants go marching 2 by 2,

tO GET OUT OF THE RAIN, boom! boom! boom!

tO GET OUT OF THE RAIN, boom! boom! boom!

(and adds this as well)To get out of the rain, BOOM! BOOM! BOOM!


Solution

  • I think you might want to call the .strip() on the string that you print the first, not print it again:

    print(l.swapcase().strip()*2)
    

    By chaining methods like this, you will strip "2" from the string and then print the stripped string twice. If you don't want to strip the "2" from the middle, call the .strip() method after you multiply the string:

    print((l.swapcase()*2).strip())
    

    EDIT: Since your string does not end with "2", the .strip() won't work as it only removes from edges. To remove all "2"s from a string, call the .replace() method on it like that:

    print(l.swapcase().replace("2", "")*2)
    

    This will replace all "2"s with an empty string, so it will pretty much remove them.