The code I have can convert a string into an integer or a float depending on the string itself.
def convert_data(data: List[List[str]]) -> None:
for sublist in data: #Accesses each element in data
for index, element in enumerate(sublist):
if element.isnumeric(): #If element is a number, check to see if it can be an int
sublist[index] = int(element) #Convert to an int
elif element.replace('.', '').isnumeric(): #If element is a number, check to see if it can be a float
sublist[index] = float(element) #convert to a float
else:
sublist[index] = sublist[index] #If it isn't a number, return the string as it is
our_data = [['no'], ['-123'], ['+5.6', '3.2'], ['3.0', '+4', '-5.0']]
convert_data(our_data)
After the function has run, our_data should be:
[['no'], [-123], [5.6, 3.2], [3, 4, -5]]
However, I get:
[['no'], ['-123'], ['+5.6', 3.2], [3.0, '+4', '-5.0']]
I need to make it so that it will convert anything with a '+' or '-' into an integer/float, instead of returning it as a string. How can I go about doing this?
I apologize if you think my code is messy, I'm just quickly trying to solve this issue I am having. Thank you for your help!