【问题标题】:Removing numbers from a given string从给定的字符串中删除数字
【发布时间】:2020-05-29 15:35:47
【问题描述】:

我正在尝试删除字符串中的任何数字。

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

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 岁 墙是,地板是 天气是,但它是

【问题讨论】:

  • 添加信息是哪种编程语言会很好,也可以添加到标签中。
  • 欢迎来到 SO!轻微的挑剔,但bluh_remover 不在代码中——您可能是指num_remover。你能展示你的实际输出与你的预期输出对比吗?谢谢。

标签: string list function numeric word


【解决方案1】:

没关系:我想通了。

除了调错函数哈哈。我能够简单地思考,只是将数字替换为空。

【讨论】:

    【解决方案2】:

    因为你已经拆分了字符串,所以它丢失了,因此,单词 Anish 将作为“Anish”出现,由于特殊字符,它不是字符串。 string = '我叫阿尼什,今年 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?
    

    【讨论】:

      【解决方案3】:

      对于任何超过 10 个单词的字符串,简单的 Replace 循环会更快。以 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-15
        • 2013-10-27
        • 1970-01-01
        相关资源
        最近更新 更多