python - 从字符串中删除数字

标签 python string

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

最佳答案

这对您的情况有用吗?

>>> 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'

关于python - 从字符串中删除数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12851791/

相关文章:

c# - 从 C# 中的其他方法访问方法的字符串

python - 提供 scrapy xpath 的备用路径

Python:没有名为unittest的模块。我怎样才能解决这个问题?

c# - 如何从组合框中删除更多项目?

string - LUA 中是否有函数可以替换字符串上的值但保留部分原始值?

c++ - 如何比较 utf8 字符串,例如 C++ 中的波斯语单词?

python - scipy 中 norm.fit 的意义是什么?

Python - 匹配和更改日期时间

python - 如何从数据框中的两列创建列表字典

c# - C++ 中的 String.Format 替代方案