0

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'

2 Answers 2

2
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
Sign up to request clarification or add additional context in comments.

4 Comments

In some cases, \b might be better than \s e.g. to catch I have 10. Though in others, it would be worse e.g. I have $10
@match correct!
is the string starts with a number it can't work
@salmamasoaudi try the edited code
0

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)

2 Comments

i dont wanna use any loop, i don't if i can use translate
if lambda function works for you then you can try result = " ".join(filter(lambda x: not x.isdigit(), str))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.