[英]Most elegant way to .format() formatted string with arbitrary length list in Python 2?
Recently I was rewriting code in which a string variable was assigned in following way: 最近,我正在重写代码,其中以以下方式分配了字符串变量:
mylist = [1.0, 2.0, 3.0]
somestring = '%6.3f' * len(mylist) % tuple(mylist)
In [7]: somestring
Out[7]: ' 1.000 2.000 3.000'
I would like to figure out how to do same using the .format()
method. 我想弄清楚如何使用
.format()
方法执行相同操作。 I ended up with following: 我最终得到以下结果:
somestring = ''.join('{:6.3f} ' for i in mylist).format(*mylist)
In [16]: somestring
Out[16]: ' 1.000 2.000 3.000 '
Is there any way to do it "better"? 有什么办法可以做到“更好”吗? (also in one line?)
(也是一行吗?)
Just as you can use %
on the multiplied string, you can use .format()
on the multiplied string. 正如您可以在已乘字符串上使用
%
一样,也可以在已乘字符串上使用.format()
。 You need to use parentheses to keep it contained, though: 但是,您需要使用括号将其包含起来:
somestring = ('{:6.3f}' * len(mylist)).format(*mylist)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.