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

1 Answers1

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)
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • 1
    I'd remove the square brackets. Generator expression will suffice and save some memory. – user2390182 Jan 22 '17 at 21:16
  • 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 Jan 22 '17 at 21:16
  • @Kobbi You should read some of the [documentation on the topic](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions). – user2390182 Jan 22 '17 at 21:17
  • 1
    @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: http://stackoverflow.com/questions/37782066/list-vs-generator-comprehension-speed-with-join-function – Jean-François Fabre Jan 22 '17 at 21:19
  • @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! – user2390182 Jan 22 '17 at 21:22
  • don't worry, I also find the `([])` thing ugly and gotten aware of that performance difference a few months ago. `join` is an exception to the gencomp stuff. – Jean-François Fabre Jan 22 '17 at 21:23