从字符串中删除数字


问题内容

在这里很难说出要问什么。这个问题是模棱两可,含糊,不完整,过于宽泛或夸张的,不能以目前的形式合理地回答。如需帮助澄清此问题以便可以重新打开,
请访问帮助中心

8年前关闭。

如何删除字符串中的数字?


问题答案:

这适合您的情况吗?

>>> s = '12abcd405'
>>> result = ''.join([i for i in s if not i.isdigit()])
>>> result
'abcd'

这利用了列表推导,这里发生的事情类似于此结构:

no_digits = []
# Iterate through the string, adding non-numbers to the no_digits list
for i in s:
    if not i.isdigit():
        no_digits.append(i)

# Now join all elements of the list with '', 
# which puts all of the characters together.
result = ''.join(no_digits)

正如@AshwiniChaudhary和@KirkStrauser指出的那样,您实际上不需要在单行代码中使用括号,从而使括号内的片段成为生成器表达式(比列表理解更有效)。即使这不符合您的分配要求,但最终还是应该阅读以下内容:):

>>> s = '12abcd405'
>>> result = ''.join(i for i in s if not i.isdigit())
>>> result
'abcd'