删除附加到单词Python的所有数字

2024-04-24 22:12:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一根绳子

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

我想得到

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

我该怎么做?你知道吗

这是我现有的代码:

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):]

但它又回来了

'Dogs are highly variable1 n1 hight and weight. 123'

Tags: and代码invariableareheightweightdogs
1条回答
网友
1楼 · 发布于 2024-04-24 22:12:28

给定的

import string


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

代码

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())

演示

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

细节

我们使用生成器通过generator expression生成独立数字(带标点或不带标点)或过滤词。你知道吗

相关问题 更多 >