Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python3: Looping over a string

I would like to program something in python3 and do not understand where my mistake is.

seq = ('1gnadutnpawihv\n  casc341')

check = ('0','1', '2', '3', '4', '5', '6', '7', '8', '9')

while i < len(seq):
    for j in range(len(check)):
        if seq[i] == check[j]:
            seq=seq.replace(seq[i],"")
            

seq=seq.replace("\n","")
seq=seq.replace(" ","")

seq

I want to eliminate the characters "\n", " ", and all numbers from 0 to 9 from the string seq with the replace function. Now I want to iterate over the seq and compare each character with each character of the tuple check and detect the numbers 0 to 9 and replace them afterwards with nothing.
The replacement method works for "\n" and " ", but not for the numbers.
The output is simply:

'1gnadutnpawihvcasc341'

Why doesn’t it work?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem was with the outer while loop. Instead of fixing it I removed it because it was redundant. I also removed the \n and spaces in the same loop:

seq = ('1gnadutnpawihv\n  casc341')
check = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '\n', ' ')

for j in range(len(check)):
    seq = seq.replace(check[j], "")

print(seq)

Output:

gnadutnpawihvcasc
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading