如何在 Python 中消除字符串中的数字?

pythonprogramming

您可以创建一个数组来跟踪字符串中的所有非数字字符。然后最后使用".join"方法连接此数组。

示例

my_str = 'qwerty123asdf32'
non_digits = []
for c in my_str:
   if not c.isdigit():
      non_digits.append(c)
result = ''.join(non_digits)
print(result)

输出

这将给出输出

qwertyasdf

示例

您还可以使用一行中的 Python 列表推导来实现这一点。

my_str = 'qwerty123asdf32'
result = ''.join([c for c in my_str if not c.isdigit()])
print(result)

输出

这将给出输出

qwertyasdf

相关文章