如何在Python中使用不带0x的hex()?

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

python中的hex()函数将前导字符0x放在数字前面。无论如何,有没有告诉它不要放它们?因此0xfa230将是fa230

代码为

1
2
3
4
5
6
import fileinput
f = open('hexa', 'w')
for line in fileinput.input(['pattern0.txt']):
   f.write(hex(int(line)))
   f.write('\
'
)


1
2
>>> format(3735928559, 'x')
'deadbeef'


使用此代码:

1
'{:x}'.format(int(line))

它也允许您指定数字位数:

1
2
'{:06x}'.format(123)
# '00007b'

对于Python 2.6使用

1
'{0:x}'.format(int(line))

1
'{0:06x}'.format(int(line))


您只需编写

1
hex(x)[2:]

删除前两个字符。


Python 3.6:

1
2
3
>>> i = 240
>>> f'{i:02x}'
'f0'

旧样式的字符串格式:

1
2
In [3]:"%02x" % 127
Out[3]: '7f'

新样式

1
2
In [7]: '{:x}'.format(127)
Out[7]: '7f'

使用大写字母作为格式字符会产生大写十六进制

1
2
In [8]: '{:X}'.format(127)
Out[8]: '7F'

文档在这里。


虽然前面的所有答案都行得通,但其中许多警告都不能同时处理正数和负数,或者只能在Python 2或3中使用。下面的版本在Python 2和3中都适用,并且适用于正数和负数:

由于Python从hex()返回字符串的十六进制值,因此我们可以使用string.replace删除0x字符,而不管它们在字符串中的位置如何(这很重要,因为这对于正数和负数都是不同的)。

1
hexValue = hexValue.replace('0x','')