如何在 Python 中删除字符串中的数字?
你可以创建一个数组来追踪字符串中所有非数字字符。最后使用 "".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
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
示例
你也可以使用一行 Python 列表推导来实现这一点。
my_str = 'qwerty123asdf32' result = ''.join([c for c in my_str if not c.isdigit()]) print(result)
输出
这会得到以下输出
qwertyasdf
广告