从字符串中删除数字
问题内容:
问题答案:
这适合您的情况吗?
>>> 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'