从字符串中删除数字 [英] Removing numbers from string
本文介绍了从字符串中删除数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从字符串中删除数字?
解决方案
这是否适合您的情况?
<预><代码>>>>s = '12abcd405'>>>result = ''.join([i for i in s if not i.isdigit()])>>>结果'A B C D'这里使用了列表推导式,这里发生的事情类似于这个结构:
no_digits = []# 遍历字符串,将非数字添加到 no_digits 列表中对于我在 s:如果不是 i.isdigit():no_digits.append(i)# 现在用''连接列表的所有元素,# 将所有字符放在一起.结果 = ''.join(no_digits)
正如@AshwiniChaudhary 和@KirkStrauser 指出的那样,您实际上不需要在单行中使用括号,从而使括号内的部分成为生成器表达式(比列表理解更有效).即使这不符合您的作业要求,您最终也应该阅读它:) :
<预><代码>>>>s = '12abcd405'>>>result = ''.join(i for i in s if not i.isdigit())>>>结果'A B C D'How can I remove digits from a string?
解决方案
Would this work for your situation?
>>> s = '12abcd405'
>>> result = ''.join([i for i in s if not i.isdigit()])
>>> result
'abcd'
This makes use of a list comprehension, and what is happening here is similar to this structure:
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)
As @AshwiniChaudhary and @KirkStrauser point out, you actually do not need to use the brackets in the one-liner, making the piece inside the parentheses a generator expression (more efficient than a list comprehension). Even if this doesn't fit the requirements for your assignment, it is something you should read about eventually :) :
>>> s = '12abcd405'
>>> result = ''.join(i for i in s if not i.isdigit())
>>> result
'abcd'
这篇关于从字符串中删除数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文