3

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'
pylang
  • 40,867
  • 14
  • 129
  • 121
u5ele55
  • 33
  • 4
  • 1
    Think about what i and char are as you remove characters from the string. – Carcigenicate Aug 02 '19 at 18:23
  • 1
    Removing items while iterating over a sequence can cause problems - https://sopython.com/canon/95/removing-items-from-a-list-while-iterating-over-the-list/ . You would be better off constructing a new string out of characters that are `not char.isdigit`. ... [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – wwii Aug 02 '19 at 18:28
  • Do you want to remove digits that are not attached to a word? For example, what result do you want if `somestr = 'I have 8 dogs'`? – Rory Daulton Aug 02 '19 at 18:36
  • You'll have to explain what "that close to word" means. – pylang Aug 02 '19 at 18:37
  • You mean only digits that *are* attached to a word must be removed, right? E.g. all digits were removed in your output "Dogs are highly variable in height and weight'" – pylang Aug 02 '19 at 18:40
  • Yes, only digits that are attached to a word must be removed – u5ele55 Aug 02 '19 at 18:43

1 Answers1

4

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.

pylang
  • 40,867
  • 14
  • 129
  • 121