This tutorial will discuss about unique ways to convert a list of floats to a list of strings in Python.
Table Of Contents
Method 1: Using List Comprehension and str()
Iterate over all elements of List using a for loop. During iteration convert each float to a string using the str()
method, and construct a new list of these strings using List Comprehension
.
Let’s see the complete example,
listOfFloats = [11.1, 12.4, 13.7, 15.9, 18.1, 29.8] # convert list of floats to list of strings listOfStrs = [str(elem) for elem in listOfFloats] print(listOfStrs)
Output
['11.1', '12.4', '13.7', '15.9', '18.1', '29.8']
Method 2: Using map() function
Pass the str()
method, and list of floats to the map()
function. It will apply str()
method on each float in the list, to convert it to a string. It stores all the converted strins into a mapped object. Then convert that mapped object into a list of strings using list()
method.
Let’s see the complete example,
Frequently Asked:
- Create List of single item repeated N times in Python
- Python List copy()
- Get sum of numbers in a list
- Get List of Unique Dictionaries in Python
listOfFloats = [11.1, 12.4, 13.7, 15.9, 18.1, 29.8] # convert list of floats to list of strings listOfStrs = list(map(str, listOfFloats)) print(listOfStrs)
Output
['11.1', '12.4', '13.7', '15.9', '18.1', '29.8']
Method 3: Using NumPy Array
Construct a NumPy Array from list, but pass the dtype
as str
in the array constructor along with the list of floats. It will create a NumPy Array of strings, by converting the floats in list to strings. Then convert this array of strings into a list of strings.
This way we can convert a list of floats to a list of strings.
Let’s see the complete example,
import numpy as np listOfFloats = [11.1, 12.4, 13.7, 15.9, 18.1, 29.8] # convert list of floats to list of strings listOfStrs = np.array(listOfFloats, str).tolist() print(listOfStrs)
Output
['11.1', '12.4', '13.7', '15.9', '18.1', '29.8']
Summary
We learned about different ways to construct a list of strings from a list of floats in Python.