Convert String Float to Float List in Python (original) (raw)

Last Updated : 06 Feb, 2025

We are given a string float we need to convert that to float of list. For example, s = ‘1.23 4.56 7.89’ we are given a list a we need to convert this to float list so that resultant output should be [1.23, 4.56, 7.89].

Using split() and map()

By using split() on a string containing float numbers, we can break it into individual string elements and then apply map() to convert each element into a float. This produces a list of floats derived from the original string.

Python `

s = '1.23 4.56 7.89'

Split the string 's' into a list of substrings and convert each substring to a float using map

f = list(map(float, s.split())) print(f)

`

**Explanation:

Using List Comprehension

We can split a string into individual elements and convert each element to a float in one line using list comprehension, resulting in a concise list of float values from the original string.

Python `

s = '1.23 4.56 7.89' # Define a string 's' containing float values separated by spaces

Use list comprehension to split the string and convert each element to a float

f = [float(x) for x in s.split()] print(f)

`

**Explanation:

Using re.split()

re.split() function can be used to split a string based on a regular expression pattern (such as spaces or other delimiters) and then map() or a list comprehension can convert each substring into a float. This method provides greater flexibility in handling different delimiters when splitting the string.

Python `

import re
s = '1.23,4.56;7.89'

Use re.split() to split the string by both commas and semicolons

f = [float(x) for x in re.split('[,;]', s)] print(f)

`

**Explanation:

Similar Reads