Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join float list into space-separated string in Python

Tags:

python

list

I have a list of floats in python:

a = [1.2, 2.9, 7.4] 

I want to join them to produce a space-separated string - ie.:

1.2 2.9 7.4 

However, when I try:

print " ".join(a) 

I get an error because they're floats, and when I try:

print " ".join(str(a)) 

I get

[ 1 . 2 ,   1 . 8 ,   5 . 2 9 9 9 9 9 9 9 9 9 9 9 9 9 9 8 ] 

How can I join all of the elements, while converting the elements (individually) to strings, without having to loop through them all?

like image 731
robintw Avatar asked Jun 28 '11 13:06

robintw


People also ask

How do you join a space-separated string in Python?

The join() method is a string method and returns a string in which the elements of sequence have been joined by str separator.

How do I convert a float list to a string in Python?

The most Pythonic way to convert a list of floats fs to a list of strings is to use the one-liner fs = [str(x) for x in fs] . It iterates over all elements in the list fs using list comprehension and converts each list element x to a string value using the str(x) constructor.

How do you join a list into a string in Python?

The most pythonic way of converting a list to string is by using the join() method. The join() method is used to facilitate this exact purpose. It takes in iterables, joins them, and returns them as a string. However, the values in the iterable should be of string data type.


1 Answers

You need to convert each entry of the list to a string, not the whole list at once:

print " ".join(map(str, a)) 

If you want more control over the conversion to string (e.g. control how many digits to print), you can use

print "".join(format(x, "10.3f") for x in a) 

See the documentation of the syntax of format specifiers.

like image 69
Sven Marnach Avatar answered Sep 29 '22 10:09

Sven Marnach