python3:{} 内的可变长度值,用于 print & .format()

python3: variable length values inside {} for print & .format()

是否可以通过灵活的 {} 调整在 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.'

但是有没有一种方法可以使 "distance between A and 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.'

或者有什么其他简单方便的方法可以实现吗?

这不是很漂亮,但这是一种方式:

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)

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)

您可以在 "Nesting arguments and more complex examples" here 下查看更多示例。