How can I eliminate numbers in a string in Python?

PythonProgramming

You can create an array to keep track of all non digit characters in a string. Then finally join this array using "".join method. 

example

my_str = 'qwerty123asdf32'
non_digits = []
for c in my_str:
   if not c.isdigit():
      non_digits.append(c)
result = ''.join(non_digits)
print(result)

Output

This will give the output

qwertyasdf

example

You can also achieve this using a python list comprehension in a single line. 

my_str = 'qwerty123asdf32'
result = ''.join([c for c in my_str if not c.isdigit()])
print(result)

Output

This will give the output

qwertyasdf
raja
Published on 20-Apr-2018 12:30:00
Advertisements