Convert String float to float list in Python

Sometimes, while working with data, we could be dealing with numbers, that are in decimal and not integers. This is general case in data science domain. Let’s discuss how to resolve a problem in which we may have a comma separated float numbers and we need to convert to float list.

Method #1 : Using list comprehension + split() + float()
The combination of above methods can be used to perform this task. In this, we convert the String to string list using split and then convert the string to float using float().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Convert String float to float list
# using list comprehension + split() + float()
  
# initializing string 
test_str = "3.44, 7.8, 9.12, 100.2, 6.50"
  
# printing original string 
print("The original string is : " + test_str)
  
# Convert String float to float list
# using list comprehension + split() + float()
res = [float(idx) for idx in test_str.split(', ')]
  
# printing result
print("The float list is : " + str(res))

chevron_right


Output :

The original string is : 3.44, 7.8, 9.12, 100.2, 6.50
The float list is : [3.44, 7.8, 9.12, 100.2, 6.5]

 

Method #2 : Using map() + split() + float()
The combination of above functions can also be used to solve this problem. In this, we perform the task of extending logic to entire list usin map(), rest all the functionalities are performed as above method.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Convert String float to float list
# using map() + split() + float()
  
# initializing string 
test_str = "3.44, 7.8, 9.12, 100.2, 6.50"
  
# printing original string 
print("The original string is : " + test_str)
  
# Convert String float to float list
# using map() + split() + float()
res = list(map(float, test_str.split(', ')))
  
# printing result
print("The float list is : " + str(res))

chevron_right


Output :

The original string is : 3.44, 7.8, 9.12, 100.2, 6.50
The float list is : [3.44, 7.8, 9.12, 100.2, 6.5]



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.