简体   繁体   中英

Join float list into space-separated string in Python

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?

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 (eg 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 .

Actually you have to loop through them. With a generator or list comprehension that looks pretty clean:

print " ".join(str(i) for i in a)

(map loops through them, as does the format code)

The generator has the advantage over the list comprehension of not generating a second intermediate list, thus preserving memory. List comprehension would be:

print " ".join([str(i) for i in a])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM