salma masoaudi
salma masoaudi

Reputation: 13

remove numbers from string using python

hello I have a question: How can I remove numbers from string, I know that the fasted and best way is to use translate

'hello467'.translate(None, '0123456789')

will return hello, but what if I want to remove only numbers that are not attached to a sting for example: 'the 1rst of every month I spend 10 dollars' should be 'the 1rst of every month I spend dollars' and not 'the rst of every month I spend dollars'

Upvotes: 0

Views: 105

Answers (2)

KostisPar
KostisPar

Reputation: 234

import re

s = "the 1rst of every month I spend 10 dollars"
 
result = re.sub(r"\b\d+\b", '', s)
result = re.sub("  ", ' ', result)

should give:

the 1rst of every month I spend dollars

Upvotes: 2

AJ31
AJ31

Reputation: 258

Split the string and check if the element is a digit and if not then join it to the result.

str = ("the 1rst of every month I spend 10 dollars").split(' ')
result = ' '.join([i for i in str if not i.isdigit()])
print(result)

Upvotes: 0

Related Questions