如何在Python中消除字符串中的数字?
您可以创建一个数组来跟踪字符串中所有非数字字符。然后最后使用 “”.join 方法将此数组连接起来。
更多Python相关文章,请阅读:Python 教程
示例
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