Issue
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?
Solution
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']
Answered By - Timur Shtatland
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.