You can use string formatting for this purpose:
>>> "0x{:02x}".format(13)
'0x0d'
>>> "0x{:02x}".format(131)
'0x83'
Edit: Your code suggests that you are trying to convert a string to a hexstring representation. There is a much easier way to do this (Python2.x):
>>> "abcd".encode("hex")
'61626364'
An alternative (that also works in Python 3.x) is the function binascii.hexlify().
You can use string formatting for this purpose:
>>> "0x{:02x}".format(13)
'0x0d'
>>> "0x{:02x}".format(131)
'0x83'
Edit: Your code suggests that you are trying to convert a string to a hexstring representation. There is a much easier way to do this (Python2.x):
>>> "abcd".encode("hex")
'61626364'
An alternative (that also works in Python 3.x) is the function binascii.hexlify().
You can use the format function:
>>> format(10, '02x')
'0a'
You won't need to remove the 0x part with that (like you did with the [2:])
Add length parameter to hex
hex - Python Hexadecimal - Stack Overflow
python - Formatting hex to be printed with 2 digits? - Stack Overflow
python - Format ints into string of hex - Stack Overflow
Use the format() function with a '02x' format.
>>> format(255, '02x')
'ff'
>>> format(2, '02x')
'02'
The 02 part tells format() to use at least 2 digits and to use zeros to pad it to length, x means lower-case hexadecimal.
The Format Specification Mini Language also gives you X for uppercase hex output, and you can prefix the field width with # to include a 0x or 0X prefix (depending on wether you used x or X as the formatter). Just take into account that you need to adjust the field width to allow for those extra 2 characters:
>>> format(255, '02X')
'FF'
>>> format(255, '#04x')
'0xff'
>>> format(255, '#04X')
'0XFF'
I think this is what you want:
>>> def twoDigitHex( number ):
... return '%02x' % number
...
>>> twoDigitHex( 2 )
'02'
>>> twoDigitHex( 255 )
'ff'
In python3, use this f string format:
f"0x{variable:02x}"
For maximum python2/3 compatibility, use .format():
"0x{:02x}".format(variable)
You can use string formatting for this purpose:
>>> "0x{:02x}".format(13)
'0x0d'
More detailed examples here:
How can I format an integer to a two digit hex?
Perhaps you're looking for the .zfill method on strings. From the docs:
Help on built-in function zfill: zfill(...) S.zfill(width) -> string Pad a numeric string S with zeros on the left, to fill a field of the specified width. The string S is never truncated.
Your code can be written as:
def padhexa(s):
return '0x' + s[2:].zfill(8)
assert '0x00000123' == padhexa('0x123')
assert '0x00ABCD12' == padhexa('0xABCD12')
assert '0x12345678' == padhexa('0x12345678')
I would suggest interpreting the input as a number, then using standard number-formatting routines.
padded = str.format('0x{:08X}', int(mystring, 16))
The string → int → string round trip may seem silly, but it is also beneficial in that it provides validation of the input string.