如何在python中为正十六进制数指定符号+

2024-04-25 22:51:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有正十六进制数和负十六进制数,比如:

-0x30
0x8

我想把这些转换成字符串,然后在另一个字符串中搜索。负十六进制数在转换为字符串时保留符号,但问题在于正十六进制数。我有这些作为字典的钥匙,比如:

x = {'-0x30': u'array', '0x8': u'local_res0'}

现在,我的问题是如何在带+符号的字符串中转换正十六进制数。你知道吗

我试过这样的方法:

'{0:+}'.format(number)

但是,它不起作用,因为数字不是整数而是十六进制。你知道吗


Tags: 方法字符串formatnumber字典local符号数字
2条回答

当你说to convert the positive hex numbers in strings with + sign.

你的意思是在他们之间?你知道吗

就像这样。。。你知道吗

#!/usr/bin/env python
'''
   this is a basic example using Python 3.7.3
'''
import re 

# simple data like the above
data = { hex(-48) : u'array', hex(8) : u'local_res0' }

# output: 
>> { '-0x30' : 'array', '0x8' : 'local_res0' }
#           \n

inverted_negatives = [h3x.replace('-','+') for h3x in data.keys() if re.match('-', h3x)]
# output: 
>> ['+0x30']
#           \n

regex_h3x = r'0x'
replacement = '+0x'
plus_positives = [h3x.replace(regex_h3x, replacement) for h3x in data.keys() if re.match(regex_h3x, h3x)]
# output: 
>> ['+0x8']
#           \n

您还可以尝试转换hex(-48) -> str : '-0x30'并转换它 像这样用硬模铸造int(str, bytes) -> int。。。你知道吗

 int(hex(-48), 0)
 # output: 
 -48
 #           \n

没有“hex”对象。你的十六进制值已经是字符串了。你知道吗

您可以直接操作字符串,也可以将其解析为整数,然后将其重新转换为所需格式的字符串。以下是每种方法的快速版本:

numbers = ['-0x30', '0x8']

reformatted_via_str = [numstr if numstr.startswith('-') else '+'+numstr for numstr in numbers]
reformatted_via_int = [format(num, '+#x') for num in (int(numstr, 16) for numstr in numbers)]

相关问题 更多 >