Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all digits attached to a word - Python

I have a string like

'Dogs are highly5 variable12 in1 height and weight. 123'

and I want to get

'Dogs are highly variable in height and weight. 123'

How can I do this?

Here's my existing code:

somestr = 'Dogs are highly5 variable12 in1 height and weight. 123'

for i, char in enumerate(somestr):
    if char.isdigit():
        somestr = somestr[:i] + somestr[(i+1):]

but it returns

'Dogs are highly variable1 n1 hight and weight. 123'
like image 355
u5ele55 Avatar asked Jan 20 '26 06:01

u5ele55


1 Answers

Given

import string


s = "Here is a state0ment with2 3digits I want to remove, except this 1."

Code

def remove_alphanums(s):
    """Yield words without attached digits."""
    for word in s.split():
        if word.strip(string.punctuation).isdigit():
            yield word
        else:
            yield "".join(char for char in word if not char.isdigit())

Demo

" ".join(remove_alphanums(s))
# 'Here is a statement with digits I want to remove, except this 1.'

Details

We use a generator to yield either independent digits (with or without punctuation) or filtered words via a generator expression.

like image 63
pylang Avatar answered Jan 23 '26 19:01

pylang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!