Python中setfill和setw的等价物是什么?

8 投票
2 回答
13485 浏览
提问于 2025-04-18 09:26

我现在正在把一些C++代码转换成Python,但我不知道怎么把这个部分翻译过来:

print  std::setfill('0') << std::setw(2) << std::hex << myVar << std::dec << " "

我该怎么把 std::setfill('0')std::setw(2) 转换成Python呢?

2 个回答

4

我来这里是想找一个和 std::setw(n) 功能相同的东西。顺便说一下,我用的是 '{:>n}'.format(nbr)

举个例子:

In [13]: '{:>2}'.format(1)
Out[13]: ' 1'
In [14]: '{:>2}'.format(10)
Out[14]: '10'
5

虽然没有完全一样的东西,但你可以用format函数把你想显示的每个值转换一下。想了解格式的具体写法,可以查看这个链接:https://docs.python.org/2/library/string.html#format-specification-mini-language

print '{:02x}'.format(myVar)

撰写回答