learnerPy
learnerPy

Reputation: 123

Remove all digits in a list of strings

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

Answers (4)

Daweo
Daweo

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

Rohit-Pandey
Rohit-Pandey

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

Dani Mesejo
Dani Mesejo

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

yatu
yatu

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

Related Questions