1

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Guy Markman
  • 426
  • 1
  • 4
  • 14

3 Answers3

1

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'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • But the number of zeroes is not always the same. I may have need for 0 zeroes or even 4 zeroes. – Guy Markman Mar 11 '16 at 13:55
  • @GuyMarkman: leave that to the `str.zfill()` method. It'll add enough zeros to give you a string of the requested width. Note that I told it to pad out to 2 characters, but only 1 `0` was added. – Martijn Pieters Mar 11 '16 at 14:31
  • @GuyMarkman: for your *example* you'd never add 4 zeros, because you told the string formatter to pad out to 2 digits too. – Martijn Pieters Mar 11 '16 at 14:32
0

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
Martin Evans
  • 45,791
  • 17
  • 81
  • 97
0

print(("{0:05X}".format(int("1C", 16))))

0001C

print(("{0:05X}".format(0x1C)))

0001C