擅长:python、mysql、java
<p>这对你的情况有用吗?</p>
<pre><code>>>> s = '12abcd405'
>>> result = ''.join([i for i in s if not i.isdigit()])
>>> result
'abcd'
</code></pre>
<p>这利用了列表理解,这里发生的事情与此结构类似:</p>
<pre><code>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)
</code></pre>
<p>正如@AshwiniChaudhary和@KirkStrauser所指出的,实际上不需要在一行中使用括号,使括号内的部分成为生成器表达式(比列表理解更有效)。即使这不符合你的作业要求,你最终还是应该读一读:):</p>
<pre><code>>>> s = '12abcd405'
>>> result = ''.join(i for i in s if not i.isdigit())
>>> result
'abcd'
</code></pre>