Con Vi
Con Vi

Reputation: 13

String to hexadecimal conversion - Python - ValueError: Invalid conversion specification

I need to split a four digit string to two hexadecimal numbers.

Eg: string = "ABCD" expected output = 0xAB 0xCD

I tried these statements:

>>data = "0000"
>>[byte1, byte2] = [data[:2], data[2:]]
>>byteInt = int(byte1,16)
>>byteHex = format(byteInt,'0#4x')
>>print byteHex

I am getting the error, "ValueError: Invalid conversion specification" at the line "byteHex = format(byteInt,'0#4x')"

Upvotes: 1

Views: 495

Answers (1)

Moses Koledoye
Moses Koledoye

Reputation: 78536

The leading zero in the format specification is not needed since you have not specified any alignment:

format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]

fill is conditioned on alignment:

>>> byteHex = format(byteInt,'#4x')
>>> byteHex
' 0x0'

To use the optional fill in the format specification, you should specify an alignment:

>>> byteHex = format(byteInt,'0>#4x') # left align
>>> byteHex
'0x00'

Upvotes: 1

Related Questions