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'