Python List of float to string conversion (original) (raw)

Last Updated : 28 Jan, 2025

When working with lists of floats in Python, we may often need to convert the elements of the list from float to string format. **For example, if we have a list of floating-point numbers like [1.23, 4.56, 7.89], converting them to strings allows us to perform string-specific operations or output them neatly. Let’s explore different methods to perform this conversion.

Using map()

map() function provides a very efficient way to convert all elements of a list. It applies the str() function to each element of the list.

Python `

a = [1.23, 4.56, 7.89]

Convert using map

b = list(map(str, a))

print(b)

`

Output

['1.23', '4.56', '7.89']

**Explanation:

Let’s explore some more ways and see how we can convert list of float to string in Python.

Table of Content

List Comprehension

List comprehension is a Pythonic way to iterate over the list and convert each element to a string.

Python `

a = [1.23, 4.56, 7.89]

Convert using list comprehension

b = [str(i) for i in a]

print(b)

`

Output

['1.23', '4.56', '7.89']

**Explanation:

Using for Loop

Using a for loop provides a more explicit way of converting elements in a list. This method is less concise but is useful when we want more customization.

Python `

a = [1.23, 4.56, 7.89]

Convert using for loop

b = [] for i in a: b.append(str(i))

print(b)

`

Output

['1.23', '4.56', '7.89']

**Explanation:

Using join() with map()

If we need to convert the list of floats to a single string where each element is separated by a specific delimiter, we can use map() along with str.join().

Python `

a = [1.23, 4.56, 7.89]

Convert and join elements as a string

b = ', '.join(map(str, a))

print(b)

`

**Explanation:

Using numpy

If the list is a numpy array, we can use numpy.vectorize() to perform the conversion efficiently.

Python `

import numpy as np

a = np.array([1.23, 4.56, 7.89])

Convert using numpy.vectorize

b = np.vectorize(str)(a)

print(b)

`

Output

['1.23' '4.56' '7.89']

**Explanation:

Similar Reads