Type-conversion in lists | Sololearn: Learn to code for FREE!


Type-conversion in lists

How to convert string elements in list to int and float? i have - list = ['1', '87,42', '28', '17,66', '2', '60,52'] i need - list = [1, 87.42, 28 , 17.66 , 2 , 60,52]

2/17/2018 1:07:30 PM

Sasha Kozachok

6 Answers

New Answer


This could do the job: https://code.sololearn.com/cG0G0D6HPoW6/?ref=app l = ['1', '87,42', '28', '17,66', '2', '60,52'] m = [float(x.replace(',','.')) for x in l] print(m)


I don't understand what you mean. Could you please describe in detail what your input data is and what your output should be. I assume as follows: You have a couple of numbers which are stored as strings and the decimal separator is a comma. What do you want to do with these strings? If you do this like in my first example then you get the exact values behind the commas, too. If you want to get the integers than the values behind the commas will get lost. ?!?!?!?


Thanks for answer! But i need to keep int because i have this code - l = [1, 2.3, 5, 4.2,2,23.5] for i in l: if type(i) is int: x = l.index(i) val = i * (l[(x)+1]) print (str(val)) results = 2.3 21.0 47.0 from one program's file i get such text data - ['1 line\nlenght = 87,42 m\n\n28 line\nlenght = 17,66 m\n\n2 line\nlenght = 60,52 m\n\n'] And i need to multiple lenghts of lines by count of lines and summ it. I work in an architectural firm and I need this code to simplify the calculations.)


Here's my example! check with type() function for correct type in list :) https://code.sololearn.com/cpHoYI54X0qe/?ref=app I m not sure it is what you want though :)


look at this code https://code.sololearn.com/cV3bT6N8g2Na/#py first number is amount of lines and it is int and the second is lenght of line and it is float. Finaly i need to multiply lines by lengths, one by one. For this i wrote this function.


YES!! i did it! look what i meant. https://code.sololearn.com/cV3bT6N8g2Na/#py thank for advices.