如何在Python中为正十六进制数字给出符号+

时间:2019-07-16 19:50:31

标签: python python-2.7

我有正负十六进制数字,例如:

-0x30
0x8

我想将它们转换为字符串,然后在另一个字符串中搜索。负十六进制数字在转换为字符串时会保留符号,但是问题在于正十六进制。我将这些作为字典键,例如:

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

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

我尝试过类似的事情:

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

但是,由于数字不是整数而是十六进制,所以它不起作用。

2 个答案:

答案 0 :(得分:1)

没有“十六进制”对象之类的东西。您的十六进制值已经是字符串。

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

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)]

答案 1 :(得分:0)

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

您是想在他们之间concatenate吗?

喜欢...

#!/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