1

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)
1
  • 1
    string = string.remove(i)? Strings are immutable, they can't be changed in place, so anything that changes them returns a new string. Commented Jan 22, 2017 at 21:03

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

6 Comments

I'd remove the square brackets. Generator expression will suffice and save some memory.
Alright, this is something else i saw on here but i don't quite understand how it works, could you explain to me how ( x for in x in string if not x.isdigits() ) works?
@Kobbi You should read some of the documentation on the topic.
@schwobaseggl: no it won't save memory. join needs to know the size, so it will build a list if not passed one. That'll be only slower: stackoverflow.com/questions/37782066/…
@Jean-FrançoisFabre Is that so? I have gotten used to using lazy iterables where possible, but that is useful knowledge. And in the case of join which builds an immutable string, it absolutely makes sense!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.