Python参数化格式 [英] Python Parameterize Formatting
本文介绍了Python参数化格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我想知道是否有一种参数化格式运算符的方法
So I was wondering if there was a way to parameterize the format operator
例如
>>> '{:.4f}'.format(round(1.23456789, 4))
'1.2346
但是,仍然可以做类似的事情
However, is there anyway to do something like this instead
>>> x = 4
>>> '{:.xf}'.format(round(1.23456789, x))
'1.2346
推荐答案
是的,可以通过一些字符串串联来实现.查看下面的代码:
Yes, this is possible with a little bit of string concatenation. Check out the code below:
>>> x = 4
>>> string = '{:.' + str(x) + 'f}' # concatenate the string value of x
>>> string # you can see that string is the same as '{:.4f}'
'{:.4f}'
>>> string.format(round(1.23456789, x)) # the final result
'1.2346'
>>>
,或者如果您希望在没有额外的 string
变量的情况下执行此操作:
or if you wish to do this without the extra string
variable:
>>> ('{:.' + str(x) + 'f}').format(round(1.23456789, x)) # wrap the concatenated string in parenthesis
'1.2346'
这篇关于Python参数化格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文