简体   繁体   中英

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 .

To get uppercase letters:

'x' Hex format. Outputs the number in base 16, using lowercase letters for the digits above 9.

'X' Hex format. Outputs the number in base 16, using uppercase letters for the digits above 9.

To get 2 digits:

width is a decimal integer defining the minimum field 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. This is equivalent to a fill character of '0' with an alignment type of '=' .

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 .

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?

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 :

print('Number ' + format(x, '02X'))

Or, alternatively, the whole point of str.format is that you can throw multiple things into one format string:

print('Number {:02X}'.format(x))

Or, if you're using Python 3.6 or later:

print(f'Number {x:02x}')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM