I have a lots of list of strings that look similar to this:
list = ['4', '-5', '5.763', '6.423', '-5', '-6.77', '10']
I want to convert it to a list of ints (or doubles) but the -
keeps producing an error.
In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer.
To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .
To convert a string with digits to a “double” (i.e., “float”) in Python, use the built-in function float(string) . For example, the expression float('123.456') will yield the float result 123.456 .
Use Integer.parseInt() to Convert a String to an Integer This method returns the string as a primitive type int.
>>> lst = ['4', '-5', '5.763', '6.423', '-5', '-6.77', '10']
>>> map(float, lst)
[4.0, -5.0, 5.763, 6.423, -5.0, -6.77, 10.0]
And don't use list
as a variable name
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