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

标签 python string python-2.7 string-formatting

这个:

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/

相关文章:

python - 从 cat 重定向会导致不同的 python 解释器行为

python - Django Test Client 可以用于生产中的 API 调用吗?

regex - 在 MATLAB 中检查 UTF-8 字母是否为元音字母

python - 仅给出子列表的元素(Python),查找列表中元素的索引的最有效方法是什么

shell - pip 没有卸载软件包

python - 如何让我的 Python Discord 机器人模仿所有发送的消息?

python - Pandas - Dataframe.set_index - 如何保留旧索引列

java - php 和 java 中需要相同的字符串比较函数

c++ - 是否可以在 C++ 中处理字符串流中的单个元素

python-2.7 - scrapy 网络爬虫教程中的错误