>>> 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所指出的,实际上不需要在一行中使用括号,使括号内的部分成为生成器表达式(比列表理解更有效)。即使这不符合你的作业要求,你最终还是应该读一读:):
而且,只要把它放在一起,就是经常被遗忘的
str.translate
,它的工作速度比循环/正则表达式快得多:对于Python 2:
对于Python 3:
不确定你的老师是否允许你使用过滤器,但是。。。
返回-
比循环更有效率。。。
示例:
相关问题 更多 >
编程相关推荐