How to use hex() without 0x in Python?

后端 未结 5 1760
失恋的感觉
失恋的感觉 2020-11-28 04:24

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

相关标签:
5条回答
  • 2020-11-28 04:33

    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.

    0 讨论(0)
  • 2020-11-28 04:34

    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))
    
    0 讨论(0)
  • 2020-11-28 04:34

    You can simply write

    hex(x)[2:]
    

    to get the first two characters removed.

    0 讨论(0)
  • 2020-11-28 04:39

    Python 3.6+:

    >>> i = 240
    >>> f'{i:02x}'
    'f0'
    
    0 讨论(0)
  • 2020-11-28 04:52
    >>> format(3735928559, 'x')
    'deadbeef'
    
    0 讨论(0)
提交回复
热议问题