gpt4 book ai didi

python - 在格式字符串中使用参数

转载 作者:行者123 更新时间:2023-11-28 21:15:53 24 4
gpt4 key购买 nike

这个:

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 the format_spec are substituted before the format_spec string is interpreted. This allows the formatting of a value to be dynamically specified.

但是请注意,嵌套只能深入一层。

关于python - 在格式字符串中使用参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29505576/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com