isdigit()
doesn't work here:
li=["word",'2.134123']
for i in li:
if i.isdigit():
li.remove(i)
isdigit()
doesn't work here:
li=["word",'2.134123']
for i in li:
if i.isdigit():
li.remove(i)
isdigit
does not pass the check for floats represented as a string.
The help of isdigit
specifies:
Return True if all characters in S are digits
and there is at least one character in S, False otherwise.
So, with that, your work around will be to find some other way to determine whether something does in fact pass the "number" check.
What you can do is wrap an attempt to convert each item to a float in a try/except and then append to a new list for every item that falls in to the except:
def remove_numbers(li):
numberless = []
for i in li:
try:
float(i)
except:
numberless.append(i)
return numberless
res = remove_numbers(["word",'2.134123'])
print(res)
# outputs ['word']
an alternative can be to modify the function to simply return True
or False
based on the float
test, and make use of filter to "filter" the list based on the result of the remove_numbers
method. (Thanks @Pynchia)
def not_a_float(s):
try:
float(s)
return False
except:
return True
res = filter(not_a_float, ["word", '2.134123'])
In terms of performance, there is no real advantage between the two, probably because the gain in the implementation of filter
is spent by the extra frame setup in the call to not_a_float
python3 -mtimeit -s'from remove_floats import remove_numbers_loop; from random import randint' -s'l=[str(i) if randint(0,100)< 20 else "abc"+str(i) for i in range(1000000)]' -s 'remove_numbers_loop(l)'
python3 -mtimeit -s'from remove_floats import remove_numbers_filter; from random import randint' -s'l=[str(i) if randint(0,100)< 20 else "abc"+str(i) for i in range(1000000)]' -s 'remove_numbers_filter(l)'
100000000 loops, best of 3: 0.00929 usec per loop
100000000 loops, best of 3: 0.0107 usec per loop
Isdigit doesnt work if the number have decimals. Return False in this case.
See https://docs.python.org/2/library/stdtypes.html
str.isdigit()
Return
True
if all characters in the string are digits and there is at least one character,False
otherwise.
Your string contains also the decimal dot and that's why the function returns False
.