145

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')
Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
mahmood
  • 23,197
  • 49
  • 147
  • 242

10 Answers10

262

(Recommended)

Python 3 f-strings: Answered by @GringoSuave

>>> i = 3735928559
>>> f'{i:x}'
'deadbeef'

Alternatives:

format builtin function (good for single values only)

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

And sometimes we still may need to use str.format formatting in certain situations @Eumiro

(Though I would still recommend f-strings in most situations)

>>> '{:x}'.format(3735928559)
'deadbeef'

(Legacy) f-strings should solve all of your needs, but printf-style formatting is what we used to do @msvalkon

>>> '%x' % 3735928559
'deadbeef'

Without string formatting @jsbueno

>>> i = 3735928559
>>> i.to_bytes(4, "big").hex()
'deadbeef'

Hacky Answers (avoid)

hex(i)[2:] @GuillaumeLemaître

>>> i = 3735928559
>>> hex(i)[2:]
'deadbeef'

This relies on string slicing instead of using a function / method made specifically for formatting as hex. This is why it may give unexpected output for negative numbers:

>>> i = -3735928559
>>> hex(i)[2:]
'xdeadbeef'
>>> f'{i:x}'
'-deadbeef'
jamylak
  • 128,818
  • 30
  • 231
  • 230
  • This may have been the best answer at the time, but today f-strings are a much nicer solution: https://stackoverflow.com/a/52674814/4298200 – Neuron May 19 '22 at 09:41
  • 1
    @Neuron-FreedomforUkraine Thanks I updated the answer to be a more comprehensive guide now – jamylak May 23 '22 at 00:45
  • 1
    great, happy to see you included it! I took the freedom to edit away the "update" notice. read the meta site I linked in the edit summary if you are curious – Neuron May 23 '22 at 09:21
  • Also, maybe it is worth mentioning `int.to_bytes` and `bytes.hex` - as a way that do not rely on string formatting. (I've just added a new answer using these) – jsbueno Jul 28 '22 at 14:43
  • @jsbueno I think your answer is pretty cool and gave you an upvote but do you think I should be recommending this as an alternative to eg. `f'{i:x}'` It just seems like eg. `f'{i:x}'` is easier than `i.to_bytes(4, "big").hex()` – jamylak Jul 29 '22 at 00:07
  • no - for most use cases, the f-string formatting is more straightforward, and I even mention that on my answer. It could be mentioned above as a method not involving going through string representation/manipulation - just that. – jsbueno Jul 29 '22 at 01:03
67

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
  • 207,213
  • 34
  • 299
  • 261
  • 11
    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
  • To be able to specify the number of digits is very helpful. – Fakir Jul 26 '22 at 10:05
25

You can simply write

hex(x)[2:]

to get the first two characters removed.

Guillaume Lemaître
  • 1,230
  • 13
  • 18
21

Python 3.6+:

>>> i = 240
>>> f'{i:x}'  # 02x to pad with zeros
'f0'
Gringo Suave
  • 29,931
  • 6
  • 88
  • 75
8

Old style string formatting:

In [3]: "%x" % 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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
msvalkon
  • 11,887
  • 2
  • 42
  • 38
5

'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 information about that in Python's documentation:

5

F-strings

Python 3's formatted literal strings (f-strings) support the Format Specification Mini-Language, which designates x for hexadecimal numbers. The output doesn't include 0x.

So you can do this:

>>> f"{3735928559:x}"
'deadbeef'

See the spec for other bases like binary, octal, etc.

Edit: str.removeprefix

Since Python 3.9, there is now a str.removeprefix method, which allows you to write the following more obvious code:

>>> hexadecimal = hex(3735928559)
>>> hexadecimal.removeprefix('0x')
'deadbeef'

Not that this does NOT work for negative numbers ❌:

>>> negadecimal = hex(-3735928559)
>>> negadecimal.removeprefix('0x')
'-0xdeadbeef'
Amin Shah Gilani
  • 8,675
  • 5
  • 37
  • 79
1

Besides going through string formatting, it is interesting to have in mind that when working with numbers and their hexadecimal representation we usually are dealing with byte-content, and interested in how bytes relate.

The bytes class in Python 3 had been enriched with methods over the 3.x series, and int.to_bytes combined with the bytes.hex() provide full control of the hex-digits output, while preserving the semantics of the transform (not to mention, holding the intermediate "bytes" object ready to be used in any binary protocol that requires the number):

In [8]: i = 3735928559

In [9]: i.to_bytes(4, "big").hex()
Out[9]: 'deadbeef'

Besides that, bytes.hex() allow some control over the output, such as specifying a separator for the hex digits:

In [10]: bytes.hex?
Docstring:
Create a string of hexadecimal numbers from a bytes object.

  sep
    An optional single character or byte to separate hex bytes.
  bytes_per_sep
    How many bytes between separators.  Positive values count from the
    right, negative values count from the left.

Example:
>>> value = b'\xb9\x01\xef'
>>> value.hex()
'b901ef'
>>> value.hex(':')
'b9:01:ef'
>>> value.hex(':', 2)
'b9:01ef'
>>> value.hex(':', -2)
'b901:ef'

(That said, in most scenarios just a quick print is wanted, I'd probably just go through f-string formatting, as in the accepted answer: f"{mynumber:04x}" - for the simple reason of "less things to remember")

jsbueno
  • 99,910
  • 10
  • 151
  • 209
-1

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','')

EDIT: wjandrea made a good point in that the above implementation doesn't handle values that contain 0X instead of 0x, which can occur in int literals. With this use case in mind, you can use the following case-insensitive implementation for Python 2 and 3:

import re
hexValue = re.sub('0x', '', hexValue, flags=re.IGNORECASE)
  • This works, but why remove `'0x'` when you could avoid adding it in the first place with the format spec `x`? [jamylak's answer](/a/16414603/4518341) and [Gringo Suave's answer](/a/52674814/4518341) cover it. – wjandrea Dec 21 '21 at 23:25
  • 1
    @wjandrea I'm not sure why I thought jamylak's answer didn't work on both Python 2 and 3. I just tested it on Python 2.7.2 and 3.7.8 and it worked on both of these. Also, thank you for pointing out the edge case that my original answer wasn't addressing. I've provided an updated implementation that addresses this use case as well. – Austin Patton Dec 24 '21 at 20:32
-3

Decimal to Hexadecimal, it worked

hex(number).lstrip("0x").rstrip("L")
Baxromov
  • 23
  • 5