Reputation: 446
In Python 2.7, I want to convert hex ascii number to itself using string formating with specific number of digits
Example:
hexNumber='9'
print '%02x' % (hexNumber)
Output:
09
Upvotes: 1
Views: 204
Reputation: 53
print(("{0:05X}".format(int("1C", 16))))
0001C
print(("{0:05X}".format(0x1C)))
0001C
Upvotes: 0
Reputation: 46779
You can also make use of Python's format
command for string formatting. This allows you to specify a fill character, in this case 0
and a width as follows:
print "{:0>2s}".format('9')
This would display:
09
Upvotes: 0
Reputation: 1124110
You have a string, just zero-fill it to the desired width using str.zfill()
:
hexNumber.zfill(2)
The %x
formatter is for integers only.
Demo:
>>> hexNumber = '9'
>>> hexNumber.zfill(2)
'09'
Upvotes: 1