我正试图删除一个字符串中的任何数字,但当我运行程序时,数字被删除了,但字符串的其他部分也被删除了。
然而,当我运行我的程序时,数字被删除,但字符串的其他部分也被删除。
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岁 墙壁是,地板是 天气是,但它是:
NEVERMIND。我知道了
除了调用了错误的函数外,哈哈。我能够简单的思考,只是把数字替换成什么都没有。
因为你把字符串拆开了,所以缺失了,所以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?
对于任何超过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