Removing letters from a list of both numbers and letters
python
Solution
You can use `str.translate` to filter out letters:
>>> from string import letters
>>> strs = "6483A2"
>>> strs.translate(None, letters)
'64832'
There's no need to convert a string to a list, you can iterate over the string itself.
Using `str.join`, `str.isdigit` and list comprehension:
>>> ''.join([c for c in strs if c.isdigit()])
'64832'
or this as you want the `sum` of digits:
sum(int(c) for c in strs if c.isdigit())
Timing comparisons:
Tiny string:
>>> strs = "6483A2"
>>> %timeit sum(int(c) for c in strs.translate(None, letters))
100000 loops, best of 3: 9.19 us per loop
>>> %timeit sum(int(c) for c in strs if c.isdigit())
100000 loops, best of 3: 10.1 us per loop
Large string:
>>> strs = "6483A2"*1000
>>> %timeit sum(int(c) for c in strs.translate(None, letters))
100 loops, best of 3: 5.47 ms per loop
>>> %timeit sum(int(c) for c in strs if c.isdigit())
100 loops, best of 3: 8.54 ms per loop
Worst case, all letters:
>>> strs = "A"*100
>>> %timeit sum(int(c) for c in strs.translate(None, letters))
100000 loops, best of 3: 2.53 us per loop
>>> %timeit sum(int(c) for c in strs if c.isdigit())
10000 loops, best of 3: 24.8 us per loop
>>> strs = "A"*1000
>>> %timeit sum(int(c) for c in strs.translate(None, letters))
100000 loops, best of 3: 7.34 us per loop
>>> %timeit sum(int(c) for c in strs if c.isdigit())
1000 loops, best of 3: 210 us per loop
Problem
In a function I'm trying to write, the user enters a bunch of numbers e.g. "648392". I turn this string into a list like this: ['6', '4', '8', '3', '9', '2']. I wanted to be able to do sums with these numbers so I was turning the numbers in the list into integers rather than strings. This all worked fine, however I also wanted the user to be able to enter letters, and then I would just remove them from the list - and this is where I'm stuck. For example a user entering "6483A2". I can't check to see if an element is a digit with isDigit because the elements apparently have to be integers first, and I can't convert the elements in the list to integers because some of the elements are letters... I'm sure there's a simple solution but I am pretty terrible at python, so any help would be much appreciated!