Reputation: 123
words = ['Duration12', 'Noun1', 'Adjective7']
result = [word[:-2] for word in words]
gives me
['Duration', 'Nou', 'Adjectiv']
But I want to get
['Duration', 'Noun', 'Adjective']
Is there any library function to implement it or should I explicitly detect the digits available and then remove them?
Upvotes: 2
Views: 86
Reputation: 36360
If you are sure all digits are at end of words, you might use .strip
following way:
words = ['Duration12', 'Noun1', 'Adjective7']
results = [i.strip('0123456789') for i in words]
print(results) #give ['Duration', 'Noun', 'Adjective']
but keep in mind that this method would not work if digits are inside rather than at end
Upvotes: 0
Reputation: 2159
Try This One:
In [8]: from string import digits
In [9]: remove_digits = str.maketrans('', '', digits)
In [10]: [word.translate(remove_digits) for word in words]
Out[10]: ['Duration', 'Noun', 'Adjective']
For more info refer to the link: Link
Upvotes: 2
Reputation: 61910
You can filter out the numbers, using isalpha:
words = ['Duration12', 'Noun1', 'Adjective7']
result = [''.join(c for c in w if c.isalpha()) for w in words]
print(result)
Upvotes: 0
Reputation: 88226
You could use a list comprehension and remove all digits using re.sub
:
import re
words = ['Duration12', 'Noun1', 'Adjective7']
[re.sub(r'[0-9]', '', w) for w in words]
Result
['Duration', 'Noun', 'Adjective']
Upvotes: 1