如何在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:33:17  来源:igfitidea点击:

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

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放在数字前面。反正有没有告诉它不要把它们?所以0xfa230fa230

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

Old style string formatting:

旧式字符串格式:

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

New style

新风格

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

Using capital letters as format characters yields uppercase hexadecimal

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

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

Docsare here.

文档在这里。

回答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'