[英]Python - How do I format a hexadecimal number in uppercase and two digits?
I needed to do a hexadecimal counter. 我需要做一个十六进制计数器。
I tried to do it this way: 我试图这样做:
x = 0
while(x != 10):
print('Number '+'{0:x}'.format(int(x)))
x = x + 1
The counter is working. 计数器正在工作。 The only problem is that the output looks like this
唯一的问题是输出看起来像这样
0 5 a f 14 19
1 6 b 10 15 1a
2 7 c 11 16 1b
3 8 d 12 17 1c
4 9 e 13 18 1d
and I would like it to look like this 我希望它看起来像这样
00 05 0A 0F 14 19
01 06 0B 10 15 1A
02 07 0C 11 16 1B
03 08 0D 12 17 1C
04 09 0E 13 18 1D
How could I do that? 我该怎么办?
This is explained in the Format specification Mini-Language . 这在Format规范Mini-Language中进行了说明 。
To get uppercase letters: 要获取大写字母:
'x' Hex format.
'x'十六进制格式。 Outputs the number in base 16, using lowercase letters for the digits above 9.
以16为基数输出数字,对9以上的数字使用小写字母。
'X' Hex format.
“ X”十六进制格式。 Outputs the number in base 16, using uppercase letters for the digits above 9.
以16为基数输出数字,对9以上的数字使用大写字母。
To get 2 digits: 要获得2位数字:
width is a decimal integer defining the minimum field width.
width是一个十进制整数,用于定义最小字段宽度。 If not specified, then the field width will be determined by the content.
如果未指定,则字段宽度将由内容确定。
When no explicit alignment is given, preceding the width field by a zero (
'0'
) character enables sign-aware zero-padding for numeric types.如果未给出明确的对齐方式,则在宽度字段前面加上零(
'0'
)字符可启用数字类型的符号感知零填充。 This is equivalent to a fill character of'0'
with an alignment type of'='
.这等效于对齐类型为
'='
的填充字符'0'
'='
。
So, you either need to set the width
to 2, the fill
to 0
, and the alignment
to =
, or, more simply, just use the special 0
prefix before the width
. 因此,您需要将
width
设置为2,将fill
为0
,将alignment
为=
,或者更简单地,只需在width
之前使用特殊的0
前缀。
So: 所以:
print('Number '+'{0:02X}'.format(int(x)))
While we're at it, this is pretty silly code. 当我们使用它时,这是非常愚蠢的代码。
First, x
is already an int
, so why call int
on it? 首先,
x
已经是一个int
,那么为什么要对其调用int
呢?
print('Number '+'{0:02X}'.format(x))
Meanwhile, if the only thing you're putting in a format
string is a single format specifier, you don't need str.format
, just format
: 同时,如果要输入
format
字符串的唯一内容是单个格式说明符,则不需要str.format
,只需要format
:
print('Number ' + format(x, '02X'))
Or, alternatively, the whole point of str.format
is that you can throw multiple things into one format string: 或者,
str.format
的全部str.format
是您可以将多个内容放入一个格式字符串中:
print('Number {:02X}'.format(x))
Or, if you're using Python 3.6 or later: 或者,如果您使用的是Python 3.6或更高版本:
print(f'Number {x:02x}')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.