简体   繁体   中英

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'

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM