In Python, I want to convert all strings in a list to integers.
So if I have:
list1 = ['10,20,30']
How do I make it:
list1 = [10,20,30]
try this:
list1 = [int(i) for i in list1[0].split(',')]
First of all you have to define what the array contains, for how you have wrote the questions the array is:
0: 10,20,30
if your array is made of strings like that then you should make a regex to identify the numbers in every string and then convert the number into an integer. But I think that your array is actually:
0: 10
1: 20
2: 30
In this case you would want to do:
for every number in the array
make the number an integer
which would be
for num in list:
# if the value is a string
if type(num) == str: # just to be sure
num = int(num)
In python every data type is easily changeable through int
, float
or str
, but remember to assign the number after you have converted it.
int(num)
would make a number an integer but would not actually convert it because have not stored it, you should do num = int(num)
because those are functions that return what to want, to really understand how they works mean you should search about dynamically typed languages and functions