有没有一种方法可以在Python中创建一个格式的字符串,并具有灵活的{}调整?
默认方法是:
In [1]: "{:20}Hey B! You are {} blocks away.".format("Hey A!", 20-6)
Out[1]: 'Hey A! Hey B! You are 14 blocks away.'
但是,有没有办法对" A和B之间的距离"进行编码?这样..?
#not working
In [2]: x = 20
In [3]: "{:x}Hey! You are {} blocks away.".format("Hey! A", x-6)
Out[3]: 'Hey A! Hey B! You are 14 blocks away.'
In [2]: x = 30
In [3]: "{:x}Hey! You are {} blocks away.".format("Hey! A", x-6)
Out[3]: 'Hey A! Hey B! You are 14 blocks away.'
或其他简单方便的方法可以实现它?
python允许嵌套格式化操作员。在位置操作时,每个位置参数都会按照其开放式撑杆的位置计算。因此,要根据需要使用x
来证明"Hey! A"
,您可以做:
"{:{}}Hey! You are {} blocks away.".format("Hey! A", x, x-6)
^^ These brackets fill in the desired width using the second positional arg
如果您想避免在这种情况下考虑编号,则可以将提供宽度的参数命名,并通过关键字传递,例如width
:
"{:{width}}Hey! You are {} blocks away.".format("Hey! A", x-6, width=x)
您可以在此处看到更多示例。
这并不漂亮,但这是一种方法:
x = 20
("{:"+str(x)+"}Hey! You are {} blocks away.").format("Hey! A", x-6)
# 'Hey! A Hey! You are 14 blocks away.'
替代语法:
''.join(("{:", str(x), "}Hey! You are {} blocks away.")).format("Hey! A", x-6)