这个:
print '{:x<4d}'.format(34)
打印这个:
34xx
我该怎么做:
width = 13
print '{:x<|width|d}'.format(34)
要得到这个:
34xxxxxxxxxxx
最佳答案
您可以将一个格式字段放在另一个格式字段中:
>>> width = 13
>>> print '{:x<{}d}'.format(34, width)
34xxxxxxxxxxx
>>>
来自docs :
A
format_spec
field can also include nested replacement fields within it. These nested replacement fields can contain only a field name; conversion flags and format specifications are not allowed. The replacement fields within theformat_spec
are substituted before theformat_spec
string is interpreted. This allows the formatting of a value to be dynamically specified.
但请注意,嵌套只能深入一层。
关于python - 在格式字符串中使用参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29505576/