How to convert an integer to hexadecimal without the extra '0x' leading and 'L' trailing characters in Python?

后端 未结 6 1136
栀梦
栀梦 2021-02-18 14:23

I am trying to convert big integer number to hexadecimal, but in result I get extra \"0x\" in the beginning and \"L\" at the and. Is there any way to remove them. Thanks. The nu

相关标签:
6条回答
  • 2021-02-18 14:37

    Similar to Praveen's answer, you can also directly use built-in format().

    >>> a = 44199528911754184119951207843369973680110397
    >>> format(a, 'x')
    '1fb62bdc9e54b041e61857943271b44aafb3d'
    
    0 讨论(0)
  • 2021-02-18 14:37

    I think it's dangerous idea to use strip.
    because lstrip or rstrip strips 0.

    ex)

    a = '0x0'
    a.lstrip('0x')  
    
    ''
    

    result is '', not '0'.

    In your case, you can simply use replce to prevent above situation.
    Here's sample code.

    hex(bignum).replace("L","").replace("0x","")
    
    0 讨论(0)
  • 2021-02-18 14:44

    Sure, go ahead and remove them.

    hex(bignum).rstrip("L").lstrip("0x") or "0"
    

    (Went the strip() route so it'll still work if those extra characters happen to not be there.)

    0 讨论(0)
  • 2021-02-18 14:45

    Be careful when using the accepted answer as lstrip('0x') will also remove any leading zeros, which may not be what you want, see below:

    >>> account = '0x000067'
    >>> account.lstrip('0x')
    '67'
    >>>
    

    If you are sure that the '0x' prefix will always be there, it can be removed simply as follows:

    >>> hex(42)
    '0x2a'
    >>> hex(42)[2:]
    '2a'
    >>>
    

    [2:] will get every character in the string except for the first two.

    0 讨论(0)
  • 2021-02-18 14:45

    A more elegant way would be

    hex(_number)[2:-1]
    

    but you have to be careful if you're working with gmpy mpz types, then the 'L' doesn't exist at the end and you can just use

    hex(mpz(_number))[2:]
    
    0 讨论(0)
  • 2021-02-18 14:47

    The 0x is literal representation of hex numbers. And L at the end means it is a Long integer.

    If you just want a hex representation of the number as a string without 0x and L, you can use string formatting with %x.

    >>> a = 44199528911754184119951207843369973680110397
    >>> hex(a)
    '0x1fb62bdc9e54b041e61857943271b44aafb3dL'
    >>> b = '%x' % a
    >>> b
    '1fb62bdc9e54b041e61857943271b44aafb3d'
    
    0 讨论(0)
提交回复
热议问题