Convert list of floats to string python

View Discussion

Improve Article

Save Article

• Discuss
• View Discussion

Improve Article

Save Article

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 `join()`.

`test_list ``=` `[``5.8``, ``9.6``, ``10.2``, ``45.3``, ``6.0``]`

`print``(``"The original list is : "` `+` `str``(test_list))`

`res ``=` `" "``.join([``str``(i) ``for` `i ``in` `test_list])`

`print``(``"Conversion of float list to string : "` `+` `str``(res))`

Output :

```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.

`test_list ``=` `[``5.8``, ``9.6``, ``10.2``, ``45.3``, ``6.0``]`

`print``(``"The original list is : "` `+` `str``(test_list))`

`res1 ``=` `" "``.join(``str``(test_list))`

`res2 ``=` `" "``.join(``map``(``str``, test_list))`

`print``(``"Conversion using join + str : "` `+` `str``(res1))`

`print``(``"Conversion using join + str + map : "` `+` `str``(res2))`

Output :

```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
```

I have a list of floats in Python and when I convert it into a string, I get the following

``````[1883.95, 1878.3299999999999, 1869.4300000000001, 1863.4000000000001]
``````

These floats have 2 digits after the decimal point when I created them (I believe so),

Then I used

``````str(mylist)
``````

How do I get a string with 2 digits after the decimal point?

======================

Let me be more specific, I want the end result to be a string and I want to keep the separators:

``````"[1883.95, 1878.33, 1869.43, 1863.40]"
``````

I need to do some string operations afterwards. For example `+="!\t!"`.

Inspired by @senshin the following code works for example, but I think there is a better way

``````msg = "["

for x in mylist:
msg += '{:.2f}'.format(x)+','

msg = msg[0:len(msg)-1]
msg+="]"
print msg
``````

Convert a list of floats to a list of strings in Python #

To convert a list of floats to a list of strings:

1. Use a list comprehension to iterate over the list.
2. On each iteration, pass the current float to the `str()` class.
3. The new list will only contain strings.

```Copied!```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.

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

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.

```Copied!```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`.

```Copied!```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.

```Copied!```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.

Convert a list of floats to a list of strings using map() #

To convert a list of floats to a list of strings:

1. Call the `map()` function with the `str()` class and the list of floats.
2. The `map()` function will pass each float from the list to the `str()` class.
3. Use the `list()` class to convert the `map` object to a list.

```Copied!```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.

The `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.

How do you convert a list of elements to a string in Python?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

Can you convert a float to a string?

The Float. toString() method can also be used to convert the float value to a String. The toString() is the static method of the Float class.

How do you print a float list in Python?

Use numpy..
floats = [1.234567, 3.14159, 100.2232888888888, 2.22777777277277].
floats_array = np. array(floats).
np. set_printoptions(precision=2).
print(floats_array).

Can you have a list of floats in Python?

Python is a very flexible language and allows you to add just about any type of data to a list, regardless of the data type of any of the other elements in the list. One common data type to add to a list is the float data type.

Tải thêm tài liệu liên quan đến bài viết Convert list of floats to string python