To convert a set of strings to a set of floats in Python, you can use list comprehension to convert each string into a float and then create a new set from the resulting list.
In this example,
string_set1
using the curly braces syntax, which contains the string values '1.1'
, '2.2'
, and '3.3'
.string_set1
into a float using the float()
constructor.set()
constructor, resulting in a set of floats named float_set1
.print()
.string_set1 = {'1.1', '2.2', '3.3'}
float_set1 = set([float(s) for s in string_set1])
print(float_set1)
{1.1, 2.2, 3.3}
In this example,
string_set2
using the curly braces syntax, which contains the string values '4.4'
, 'hello'
, '5.5'
, '6.6'
, and 'world'
.string_set2
into a float using the float()
constructor.set()
constructor, resulting in a set of floats named float_set2
.print()
.string_set2 = {'4.4', 'hello', '5.5', '6.6', 'world'}
float_set2 = set([float(s) for s in string_set2])
print(float_set2)
{4.4, 5.5, 6.6}
In this tutorial, we learned How to Convert a Set of Strings to a Set of Floats in Python language with well detailed examples.