I have a function that I use to compare two strings character by character and do some additional tasks on it. I want to modify it to compare hex numbers instead.
For example: If A = "hello"
, B = "himan"
were to be compared. I used to run a for
loop and compare character by character. It worked fine.
for x, y in zip(A, B):
if x == y:
do something
How do I modify it to consider hex numbers. For example, if A = "30303867"
and B = "3f160303"
, I want to match 30
with 3f
first then so on. Normally, I can only match 3
by 3
and so on.
Thanks
If I understand you correctly, you have two strings A
and B
, but you want to interpret those strings not as characters but as pairs of hexadecimal digits. But without considering the integer values of those digits. This amounts to comparing pairs of characters, and because they are hexadecimal digits you will need to do a case-insensitive compare because when considered as hexadecimal values, 1F and 1f are equal.
This will split your strings into pairs of characters:
def digit_pairs(s):
return [s[i:i+2].lower() for i in range(0,len(s),2)]
and then you can do
for a, b in zip(digit_pairs(A),digit_pairs(B)):
if a == b:
do something
I don't understand your objection to converting to integer, though. Are you aware that integers in Python can be arbitrarily large?