Remove all the digits from list of strings in Python
In this tutorial, we are going to learn various methods to remove the digits from a list of string items in Python. To remove digits, Python has multiple libraries that we can use. We can import those libraries and using those libraries we can remove digits or any specific symbol from the string in Python.
Python program to remove all the digits from list of strings
Let us generate a random string containing a digit.
list = ['string1', 'string2', 'string3']
It can be clearly seen that the list contains string followed by a digit. Now, let us check what are the methods to remove digits from the list.
Using “regex” library:-
In Python, regex pattern can be used to remove all digits from the string. To use the “regex” library, we need to import regex as “re”. Then define a function and using for loop we can remove digits from a string.
import re
def remove(list):
pattern = '[0-9]'
list = [re.sub(pattern, '', i) for i in list]
return list
print(remove(list))As we can see from above, “regex” will remove all the digits from the list.
['string', 'string', 'string']
Using x.isalpha() method:
Using “x.isalpha( )” and using nested for loop, we can remove all digits from a string.
from string import digits def remove(list): list = [''.join(x for x in i if x.isalpha()) for i in list] return list print(remove(list))
In the above code, it can be seen that It will check if the characters of the string are an alphabet or not. If it is the alphabet, join it within the list, otherwise leave it.
Here is the output:
['string', 'string', 'string']
Leave a Reply