Home > Net >  Removing only the number from every item in a python list (whilst keeping the words)
Removing only the number from every item in a python list (whilst keeping the words)

Time:06-18

I have a list in python in which every string also has a number as part of it, I.e:

list = ['Hello 12', 'Things 54', 'Twice 23']

I need it to become a list which retains all the original strings but without any of the number, I.e:

list = ['Hello', 'Things', 'Twice']

Is there a simple way to iterate through the list and remove only the numbers from each item in the list?

CodePudding user response:

Use list comprehension with re.sub. Here, \s* is 0 or more whitespace characters, \d is 1 or more digits.

import re
lst = ['Hello 12', 'Things 54', 'Twice 23']
lst = [re.sub(r'\s*\d ', '', s) for s in lst]
print(lst)
# ['Hello', 'Things', 'Twice']

CodePudding user response:

You can use a regexp replacement to remove all the digits.

import re

new_list = [re.sub(r'\d', '', s) for s in old_list]

CodePudding user response:

You could use a nested list comprehension along with str.isalpha and str.join:

>>> items = ['Hello 12', 'Things 54', 'Twice 23']
>>> items_sans_nums = [''.join(c for c in item if c.isalpha()) for item in items]
>>> items_sans_nums
['Hello', 'Things', 'Twice']
  • Related