python - 从字符串中删除数字
如何从字符串中删除数字?
user1739954 asked 2019-05-20T20:27:26Z
8个解决方案
120 votes
这适合你的情况吗?
>>> 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'
>>

本文提供了多种Python方法从字符串中删除数字,包括使用列表推导式、str.translate、过滤器和正则表达式等。示例代码展示了如何通过判断字符是否为数字并过滤掉来达到目的。
最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



