112

The hex() function in python, puts the leading characters 0x in front of the number. Is there anyway to tell it NOT to put them? So 0xfa230 will be fa230.

The code is

import fileinput
f = open('hexa', 'w')
for line in fileinput.input(['pattern0.txt']):
   f.write(hex(int(line)))
   f.write('\n')
mahmood
  • 19,156
  • 36
  • 118
  • 190

7 Answers7

208
>>> format(3735928559, 'x')
'deadbeef'
jamylak
  • 111,593
  • 23
  • 218
  • 220
63

Use this code:

'{:x}'.format(int(line))

it allows you to specify a number of digits too:

'{:06x}'.format(123)
# '00007b'

For Python 2.6 use

'{0:x}'.format(int(line))

or

'{0:06x}'.format(int(line))
eumiro
  • 179,099
  • 29
  • 277
  • 252
  • 9
    Using the `format()` function is easier, you are not using any templating functionality, only formatting. If all your template contains is `{:..}` for *one* value, move to `format(value, '..')` instead. – Martijn Pieters May 07 '13 at 08:33
  • Using `f.write('{:x}'.format(hex(int(line))))`, it says `ValueError: zero length field name in format` – mahmood May 07 '13 at 08:34
  • `format` needs an int, not a string: `f.write('{:x}'.format(int(line)))` – eumiro May 07 '13 at 08:35
20

You can simply write

hex(x)[2:]

to get the first two characters removed.

Guillaume Lemaître
  • 1,036
  • 9
  • 18
16

Python 3.6+:

>>> i = 240
>>> f'{i:02x}'
'f0'
Gringo Suave
  • 25,443
  • 6
  • 77
  • 69
7

Old style string formatting:

In [3]: "%02x" % 127
Out[3]: '7f'

New style

In [7]: '{:x}'.format(127)
Out[7]: '7f'

Using capital letters as format characters yields uppercase hexadecimal

In [8]: '{:X}'.format(127)
Out[8]: '7F'

Docs are here.

msvalkon
  • 10,851
  • 2
  • 37
  • 37
1

'x' - Outputs the number in base 16, using lower-case letters for the digits above 9.

>>> format(3735928559, 'x')
'deadbeef'

'X' - Outputs the number in base 16, using upper-case letters for the digits above 9.

>>> format(3735928559, 'X')
'DEADBEEF'

You can find more informations about that in Python's documentation: https://docs.python.org/3.8/library/string.html#formatspec https://docs.python.org/3.8/library/functions.html#format

0

While all of the previous answers will work, a lot of them have caveats like not being able to handle both positive and negative numbers or only work in Python 2 or 3. The version below works in both Python 2 and 3 and for positive and negative numbers:

Since Python returns a string hexadecimal value from hex() we can use string.replace to remove the 0x characters regardless of their position in the string (which is important since this differs for positive and negative numbers).

hexValue = hexValue.replace('0x','')