如何从字符串中删除数字?
最佳答案
这对您的情况有用吗?
>>> 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/