Im a beginner in python so forgive me if the answer is comical :)
I'm trying to write some code that coverts str into int and floats. I will give an example below:
if we are given this:
data = [['ab2'], ['-123'], ['BIKES', '3.2'], ['3.0', '+4', '-5.0']]
we need to return this:
data = [['ab2'], [-123], ['BIKES', 3.2], [3, 4, -5]]
I have tried in several ways to do this like so:
# first attempt
for sublist in data:
for value in range(0, len(sublist)):
if "." in sublist[value]:
sublist[value] = float(sublist[value])
elif sublist[value].isnumeric():
sublist[value] = int(sublist[value])
# second attempt
for sublist in data:
for value in sublist:
if value.isnumeric():
if int(value) == float(value):
value = int(value)
else:
value = float(value)
I keep coming back to the same few problems though:
- the isnumeric or isdigit doesn't accept "-", "+" or "." in the answer, so if i have "-123.4" thats not a number
- Numbers like 3.0 or 4.0, need to be converted into integers and not floats
- I need a way to mutate the original list and basically "replace' the old numbers, with new
I know you can use try/except blocks but i haven't studied those and I don't understand them, so if anyone could give me some guidance on what to do, or how to alter my code, it would be greatly appreciated :)
Thanks