Reputation: 3
The homework problem requires me to download a csv and convert it into a list in order to clean it up.
The list has both integers and and strings, and I need to use some kind of try and except statement to float the numeric values and the except statement to ignore the values with a string and continue converting the numeric values.
The list is as follows
raw_pd =['002', 'Ivysaur', 'GrassPoison', '405', '60', '62', '63', '80', '80', '60']
I've tried multiple for loops with try and except but none of them seem to get the desired result.
for item in raw_pd:
try:
float(item)
except:
pass
the result is unchanged
I also tried
for item in raw_pd:
try:
int(item)
except:
print("This isn't an integer")
I expected the values to look like:
[002, 'Ivysaur', 'GrassPoison', 405, 60, 62, 63, 80, 80, 60]
but when I look at the list again everything is still a float
Upvotes: 0
Views: 148
Reputation: 281
You can as an alternative to the above answers use .isalpha() to check if the elements in the list contain only alphabetic characters and thereby find which ones are numeric, as when using .isnumeric() on a negative number you will get a False response.
Let me know if this helped! Cheers!
Upvotes: 0
Reputation: 1009
As @Reblochon Masque says, you can use isdigit()
to test whether a string is digit or nor. The code you want is:
raw_pd = ['002', 'Ivysaur', 'GrassPoison', '405', '60', '62', '63', '80', '80', '60']
pd = [float(elt) if elt.isdigit() else elt for elt in raw_pd]
print(pd)
output:
[2.0, 'Ivysaur', 'GrassPoison', 405.0, 60.0, 62.0, 63.0, 80.0, 80.0, 60.0]
Upvotes: 0
Reputation: 36702
You can do this directly inside a list comprehension by first checking if the elements are composed of digits:
raw_pd = ['002', 'Ivysaur', 'GrassPoison', '405', '60', '62', '63', '80', '80', '60']
[float(elt) for elt in raw_pd if elt.isdigit()]
[2.0, 405.0, 60.0, 62.0, 63.0, 80.0, 80.0, 60.0]
Upvotes: 1
Reputation: 2810
Casting to int
or float
doesn't change the value in your list, it operates on the input value and returns a new int or float.
x = '42'
int(x)
print(x)
'42'
y = '24'
y = int(y)
print(y)
24
Hope this helps.
Upvotes: 0