Reputation: 11496
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?
Upvotes: 8
Views: 15957
Reputation: 365975
print(f'Number {x:02x}')
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))
If you are using >= Python 3.6, you can use elegant f-strings:
print(f'Number {x:02x}')
Upvotes: 12