Sometimes, while working with Python list, we can have a problem in which we have to transform the list elements to string. This is easier in case of integral list, as they can be joined easily with
join(), and their contents can be displayed. But the case with floats is different, there are additional undesired spaces among it’s values that can cause it’s unsuccess. Let’s discuss a ways in which this error situation can be handled.
Method #1 : Using list comprehension +
join() + str()
This task can be performed using combination of above functions. In this, we firstly convert each element of list i.e float point number to string and then join the resultant strings using the
The original list is : [5.8, 9.6, 10.2, 45.3, 6.0] Conversion of float list to string : 5.8 9.6 10.2 45.3 6.0
Method #2 : Using
join() + map() + str()
The root method is similar by using the combination of
join() + str(), but important function which helps to perform this task is
map(). This first converts each element to string and then constructs the master string.
The original list is : [5.8, 9.6, 10.2, 45.3, 6.0] Conversion using join + str : [ 5 . 8, 9 . 6, 1 0 . 2, 4 5 . 3, 6 . 0 ] Conversion using join + str + map : 5.8 9.6 10.2 45.3 6.0
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.