简体   繁体   English

Python 2中具有任意长度列表的.format()格式化字符串的最优雅方法?

[英]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.

相关问题 Python:以最优雅的方式拆分这个长度结构的字符串 - Python: split this length-structured string the most elegant way python:用元素散布列表的最优雅方式 - python: most elegant way to intersperse a list with an element 打印格式化列表以及python中的索引值的优雅方法? - Elegant way to print formatted list together with index values in python? 在Python中格式化多行字符串的最优雅方式 - Most elegant way to format multi-line strings in Python 在Python中以字符串格式对日期列表进行排序的最有效方法是什么? - What is the most efficient way to sort a list of dates in string format in Python? Python,如何以最优雅的方式将任意变量从 function 传递给 function? - Python, how to pass arbitrary variables from function to function in the most elegant way? 最优雅的方法来计算Python中作业列表的完成时间 - Most elegant way to calculate completion times for a list of jobs in Python 最优雅的方式来分离基于模式的列表(Python) - Most elegant way to separate list based on pattern (Python) Python 2:使用字符串解释进行枚举的最优雅/ pythonic方式是什么? - Python 2: What is the most elegant/pythonic way of doing a enum with string interpretations? 在Python中,是否有一种优雅的方式以自定义格式打印列表而无需显式循环? - In Python, is there an elegant way to print a list in a custom format without explicit looping?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM