Print a variable in hexadecimal in Python

后端 未结 6 1395
盖世英雄少女心
盖世英雄少女心 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:53

    Use

    print " ".join("0x%s"%my_string[i:i+2] for i in range(0, len(my_string), 2))
    

    like this:

    >>> my_string = "deadbeef"
    >>> print " ".join("0x%s"%my_string[i:i+2] for i in range(0, len(my_string), 2))
    0xde 0xad 0xbe 0xef
    >>>
    

    On an unrelated side note ... using string as a variable name even as an example variable name is very bad practice.

提交回复
热议问题