I have a list which contains numbers and letters in string format.
mylist=['1','orange','2','3','4','apple']
I need to come up with a new list which only contains numbers:
mynewlist=['1','2','3','4']
If I have a way to check if each item in list can be converted to Integer, I should be able to come up with what I want by doing something like this:
for item in mylist: if (check item can be converted to integer): mynewlist.append(item)
How do I check that a string can be converted to an integer? Or is there any better way to do it?
A list of integers is defined and is displayed on the console. The 'all' operator is used to check if every element is a digit or not. This is done using the 'isdigit' method. The result of this operation is assigned to a variable.
Python list can contain duplicate elements.
As we know that list can hold duplicate values but will not update if it contains duplicate values. I tried to convert the list to Set or Map to hold unique values but the problem is we cannot perform DML operation on Set ot Map.
Try this:
mynewlist = [s for s in mylist if s.isdigit()]
From the docs:
str.isdigit()
Return true if all characters in the string are digits and there is at least one character, false otherwise.
For 8-bit strings, this method is locale-dependent.
As noted in the comments, isdigit()
returning True
does not necessarily indicate that the string can be parsed as an int via the int()
function, and it returning False
does not necessarily indicate that it cannot be. Nevertheless, the approach above should work in your case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With