Reputation: 33
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'
Upvotes: 3
Views: 89
Reputation: 44605
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.
Upvotes: 4