如何在 Python 中使用没有 0x 的 hex()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16414559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use hex() without 0x in Python?
提问by mahmood
The hex()function in python, puts the leading characters 0xin front of the number. Is there anyway to tell it NOT to put them? So 0xfa230will be fa230.
hex()python中的函数,将前导字符0x放在数字前面。反正有没有告诉它不要把它们?所以0xfa230会fa230。
The code is
代码是
import fileinput
f = open('hexa', 'w')
for line in fileinput.input(['pattern0.txt']):
f.write(hex(int(line)))
f.write('\n')
采纳答案by jamylak
>>> format(3735928559, 'x')
'deadbeef'
回答by eumiro
Use this code:
使用此代码:
'{:x}'.format(int(line))
it allows you to specify a number of digits too:
它也允许您指定多个数字:
'{:06x}'.format(123)
# '00007b'
For Python 2.6 use
对于 Python 2.6 使用
'{0:x}'.format(int(line))
or
或者
'{0:06x}'.format(int(line))
回答by msvalkon
回答by Guillaume Lema?tre
You can simply write
你可以简单地写
hex(x)[2:]
to get the first two characters removed.
删除前两个字符。
回答by Gringo Suave
Python 3.6+:
Python 3.6+:
>>> i = 240
>>> f'{i:02x}'
'f0'

