python - Removing letters from a list of both numbers and letters -


in function i'm trying write, user enters bunch of numbers e.g. "648392". turn string list this: ['6', '4', '8', '3', '9', '2'].

i wanted able sums these numbers turning numbers in list integers rather strings. worked fine, wanted user able enter letters, , remove them list - , i'm stuck. example user entering "6483a2".

i can't check see if element digit isdigit because elements apparently have integers first, , can't convert elements in list integers because of elements letters... i'm sure there's simple solution pretty terrible @ python, appreciated!

you can use str.translate filter out letters:

>>> string import letters >>> strs = "6483a2" >>> strs.translate(none, letters) '64832' 

there's no need convert string list, can iterate on string itself.

using str.join, str.isdigit , list comprehension:

>>> ''.join([c c in strs if c.isdigit()]) '64832' 

or want sum of digits:

sum(int(c) c in strs if c.isdigit()) 

timing comparisons:

tiny string:

>>> strs = "6483a2" >>> %timeit sum(int(c) c in strs.translate(none, letters)) 100000 loops, best of 3: 9.19 per loop >>> %timeit sum(int(c) c in strs if c.isdigit()) 100000 loops, best of 3: 10.1 per loop 

large string:

>>> strs = "6483a2"*1000 >>> %timeit sum(int(c) c in strs.translate(none, letters)) 100 loops, best of 3: 5.47 ms per loop >>> %timeit sum(int(c) c in strs if c.isdigit()) 100 loops, best of 3: 8.54 ms per loop 

worst case, letters:

>>> strs = "a"*100 >>> %timeit sum(int(c) c in strs.translate(none, letters)) 100000 loops, best of 3: 2.53 per loop >>> %timeit sum(int(c) c in strs if c.isdigit()) 10000 loops, best of 3: 24.8 per loop >>> strs = "a"*1000 >>> %timeit sum(int(c) c in strs.translate(none, letters)) 100000 loops, best of 3: 7.34 per loop >>> %timeit sum(int(c) c in strs if c.isdigit()) 1000 loops, best of 3: 210 per loop 

Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -