How to convert an int to a hex string?

后端 未结 13 723
不知归路
不知归路 2020-11-28 03:27

I want to take an integer (that will be <= 255), to a hex string representation

e.g.: I want to pass in 65 and get out \'\\x41\', or

13条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 03:51

    With format(), as per format-examples, we can do:

    >>> # format also supports binary numbers
    >>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
    'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
    >>> # with 0x, 0o, or 0b as prefix:
    >>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
    'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'
    

提交回复
热议问题