亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

刪除附加到單詞的所有數字 - 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 關注
  • 106 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號