Borislav Hadzhiev
Last updated: Jul 12, 2022
Check out my new book
To convert a list of floats to a list of strings:
str()
class.list_of_floats = [1.234, 5.678, 6.789] # ✅ convert list of floats to list of strings # without rounding list_of_strings = [str(item) for item in list_of_floats] print(list_of_strings) # 👉️ ['1.234', '5.678', '6.789'] # -------------------------------------------------------- # ✅ convert list of floats to list of strings # with rounding list_of_strings = [f'{item:.2f}' for item in list_of_floats] print(list_of_strings) # 👉️ [1.23, 5.68, 6.79]
We used a list comprehension to iterate over the list of floating-point numbers.
On each iteration, we pass the current list item to the str()
class to convert
it to a string.
The new list only contains string values.
If you need to round the float values when converting to strings, use a formatted string literal.
list_of_floats = [1.234, 5.678, 6.789] list_of_strings = [f'{item:.2f}' for item in list_of_floats] print(list_of_strings) # 👉️ [1.23, 5.68, 6.79]
The example rounds each float to 2 digits precision after the decimal point.
Formatted string literals (f-strings) let us include expressions inside of a
string by prefixing the string with f
.
my_str = 'is subscribed:' my_bool = True result = f'{my_str} {my_bool}' print(result) # 👉️ is subscribed: True
Make sure to wrap expressions in curly braces - {expression}
.
We are also able to use the format specification mini-language in expressions in f-strings.
my_float = 3.2 result_1 = f'{my_float:.3f}' print(result_1) # 👉️ '3.200' result_2 = f'{my_float:.5f}' print(result_2) # 👉️ '3.20000' result_3 = f'{my_float:.6f}' print(result_3) # 👉️ '3.200000'
Alternatively, you can use the map()
function.
To convert a list of floats to a list of strings:
map()
function with the str()
class and the list of floats.map()
function will pass each float from the list to the str()
class.list()
class to convert the map
object to a list.list_of_floats = [1.234, 5.678, 6.789] list_of_strings = list(map(str, list_of_floats)) print(list_of_strings) # 👉️
The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.
map()
function calls the str()
class with each float from the list to convert each value to a string.The last step is to use the list()
class to convert the map
object to a
list.
Which approach you pick is a matter of personal preference. I'd go with using a list comprehension as I find it more direct and easier to read.