为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕莱坞森 2022-04-23 21:38:00
我有一个字符串'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'
查看完整描述

1 回答

?
PIPIONE

TA贡献1829条经验 获得超9个赞

给定


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.'

细节


我们使用生成器生成独立的数字(带或不带标点符号)或通过生成器表达式过滤单词。


查看完整回答
反对 回复 2022-04-23
  • 1 回答
  • 0 关注
  • 91 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信