从一个给定的字符串中删除数字

问题描述 投票:0回答:1

我正试图删除一个字符串中的任何数字,但当我运行程序时,数字被删除了,但字符串的其他部分也被删除了。

然而,当我运行我的程序时,数字被删除,但字符串的其他部分也被删除。

string = 'My name is Anish, & I am 22 years old! The wall is blue, and the floor is orange. The weather is great, but it is raining?'

def num_remover(words):
    t = words.split()
    d = [e for e in t if e.isalpha()]
    a = " ".join(d)
    return a

print(bluh_remover(string))

输出。

我的名字是我22岁 墙壁是,地板是 天气是,但它是:

string list function numeric word
1个回答
0
投票

NEVERMIND。我知道了

除了调用了错误的函数外,哈哈。我能够简单的思考,只是把数字替换成什么都没有。


0
投票

因为你把字符串拆开了,所以缺失了,所以Anish这个词会变成'Anish',因为特殊字符,所以不是字符串.string='我叫Anish,&我今年22岁! 墙壁是蓝色的,地板是橙色的。天气很好,但正在下雨?

def num_remover(words):
    new = ''
    temp = ''
    for i in words:
       if i.isdigit():
           new = new + temp
           temp = ''
       else:
           temp = temp + i
    return new + temp
print(num_remover(string))

输出。

My name is Anish, & I am  years old! The wall is blue, and the floor is orange. The weather is great, but it is raining?

0
投票

对于任何超过10个字的字符串,一个简单的替换循环会更快。例如,在VBA中。

Dim StrTxt As String, i As Long
StrTxt = "My name is Anish, & I am 22 years old! The wall is blue, and the floor is orange. The weather is great, but it is raining?"
For i = 0 To 9
  StrTxt = Replace(StrTxt, i, "")
Next
MsgBox StrTxt
© www.soinside.com 2019 - 2024. All rights reserved.