Print a variable in hexadecimal in Python

后端 未结 6 1306
盖世英雄少女心
盖世英雄少女心 2021-02-05 09:17

I\'m trying to find a way to print a string in hexadecimal. For example, I have this string which I then convert to its hexadecimal value.

my_string = \"deadbeef         


        
6条回答
  •  不知归路
    2021-02-05 09:57

    Convert the string to an integer base 16 then to hexadecimal.

    print hex(int(string, base=16))
    

    These are built-in functions.

    http://docs.python.org/2/library/functions.html#int

    Example

    >>> string = 'AA'
    >>> _int = int(string, base=16)
    >>> _hex = hex(_int)
    >>> print _int
    170
    >>> print _hex
    0xaa
    >>> 
    

提交回复
热议问题