Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove strings from a list that contains numbers in python [duplicate]

Tags:

python

Is there a short way to remove all strings in a list that contains numbers?

For example

my_list = [ 'hello' , 'hi', '4tim', '342' ]

would return

my_list = [ 'hello' , 'hi']
like image 729
user1506145 Avatar asked Apr 18 '13 13:04

user1506145


People also ask

How do I remove a specific repeated item from a list in Python?

The method unique() from Numpy module can help us remove duplicate from the list given. The Pandas module has a unique() method that will give us the unique elements from the list given. The combination of list comprehension and enumerate is used to remove the duplicate elements from the list.

How do you remove duplicates from a list in Python with for loop?

To remove duplicates using for-loop , first you create a new empty list. Then, you iterate over the elements in the list containing duplicates and append only the first occurrence of each element in the new list. The code below shows how to use for-loop to remove duplicates from the students list. Voilà!

How do I remove a string from a list of integers in Python?

How to Remove an Element from a List Using the remove() Method in Python. To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method. remove() will search the list to find it and remove it.

How do you delete a repeating string in Python?

1) Sort the elements. 2) Now in a loop, remove duplicates by comparing the current character with previous character. 3) Remove extra characters at the end of the resultant string.


2 Answers

Without regex:

[x for x in my_list if not any(c.isdigit() for c in x)]
like image 137
eumiro Avatar answered Oct 08 '22 23:10

eumiro


I find using isalpha() the most elegant, but it will also remove items that contain other non-alphabetic characters:

Return true if all characters in the string are alphabetic and there is at least one character, false otherwise. Alphabetic characters are those characters defined in the Unicode character database as “Letter”

my_list = [item for item in my_list if item.isalpha()]
like image 28
Adam Avatar answered Oct 08 '22 22:10

Adam