繁体   English   中英

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

[英]How to give sign + for positive hex numbers in python

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

-0x30
0x8

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

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

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

我已经尝试过类似的东西:

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

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

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

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

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

当您说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(str, bytes) -> int就像这样...

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM