Kobbi
Kobbi

Reputation: 129

Removing Numbers From String Using List Python

so I'm trying to remove numbers from a string using a list of numbers from 0,9. I've been trying to figure this out for quite a while now but I haven't gotten far with it, i'll put the code down here, hopefully someone can help me with this. I don't wan't to use ways that i'm not familiar with like lambda or something I saw earlier here on stackoverflow.

string = input("Type a string: ")

numbers = ["0","1","2","3","4","5","6","7","8","9"]
start = 0

for i in range(len(string)):
    if(string[i] == numbers[start]):
        string.remove(i)
    else:
        print("Banana")

print(string)

Upvotes: 1

Views: 2773

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140148

You shouldn't iterate & try to change the object while iterating. This is complicated by the fact that strings are immutable (new reference is created when string content changes). Well, not a good solution, and not performant either even if you could make that work.

A pythonic & simple way of doing this would be:

new_string = "".join([x for x in string if not x.isdigit()])

(list comprehension which creates a new string keeping all the characters but the numerical ones)

could be "translated" for the non-listcomp speakers as:

l = []
for x in string:
    if not x.isdigit():
       l.append(x)
new_string = "".join(l)

Upvotes: 3

Related Questions