Reputation: 64064
I have a list of float which I form them into a string with the following method:
import json
a = [1.2, 2.9, 7.4]
str = "\t".join(format(x,"10.3f") for x in a)
print json.dumps(str)
However the final result of str
contain leading whitespace like this:
" 1.200\t 2.900\t 7.400"
How can I get this kind of result instead:
"1.200\t2.900\t7.400"
Upvotes: 0
Views: 174
Reputation: 2260
Numbers are padded to 10 characters because of the format you've specified.
Try to use 0
as width specifier to obtain "zero-padding for numeric types":
str = "\t".join(format(x,"0.3f") for x in a)
Have a look at python documentation: https://docs.python.org/2/library/string.html#format-specification-mini-language
Upvotes: 1
Reputation: 34176
You have to strip (using strip()
) the elements of the generator expression:
s = "\t".join(format(x, "10.3f").strip() for x in a)
Demo:
import json
a = [1.2, 2.9, 7.4]
s = "\t".join(format(x, "10.3f").strip() for x in a)
print json.dumps(s) # "1.200\t2.900\t7.400"
Note:
str
as the name of a variable because it will hide the built-in implementation of str
.Upvotes: 1