There is a list:

Х = ['d1', '2ас', '3а'] 

I need to delete all the letters so that there is a list of the following:

 Х = ['1', '2', '3'] 

3 answers 3

One of the many solutions is to use regular expressions:

 In [109]: X Out[109]: ['d1', '2ас', '3а'] In [110]: import re In [112]: XX = [re.sub('\D+', '', i) for i in X] In [113]: XX Out[113]: ['1', '2', '3'] 

this regular expression will remove all non-digits, i.e. all but numbers

    It is possible so:

     list(map(lambda x: "".join([i for i in x if i.isdigit()]), ['d1', '2ас', '3а'])) 
    • isdigit() can more than should be resolved, for example superscripts / superscripts such as '²' . Compare with string.digits , \d regex, unicode.isdecimal() (leaving behind the frame the questionable applicability of map + lambda compared to simple list comprehension). - jfs
     ords = range(48, 58) [''.join(i for i in s if ord(i) in ords) for s in X] 
    • This unreadable code ( ord(i) in range(48, 58) better expressed as char in string.digits , or (optionally) for compatibility with \d regex, as char.isdecimal() ). Go through the chain of links I gave at the top to see how different string filtering options may look and when different options are preferable to use. - jfs