6
val1 = hex(100)
val2 = hex(50)
val3 = hex(int(val1, 16) - int(val2, 16))

hex_str = str(val1) + str(val2) + str(val3)

print(hex_str)

In the above example, my end goal is to have a string that looks like this: 643232

Currently however the result I am getting has the string as 0x640x320x32

Is there a way in Python to remove the 0x from the beginning of a hex string?

Or will I have to remove it using a regular expression with something like re.sub()?

EDIT: I also need to make sure I am always getting too characters. So for example if I was looking for the hex value of 5 I'd get 05

Skitzafreak
  • 1,797
  • 7
  • 32
  • 51
  • `val1 = hex(100)[2:]` – Robᵩ Jul 26 '17 at 17:04
  • 2
    Use [string formatting](https://docs.python.org/3.4/library/string.html#formatspec) – spectras Jul 26 '17 at 17:05
  • 2
    In Python3.6: `val1 = f'{100:x}'` – Robᵩ Jul 26 '17 at 17:07
  • 2
    @Skitzafreak> full code with string formatting: `"{:x}{:x}{:x}".format(val1, val2, val3)`. – spectras Jul 26 '17 at 17:10
  • How do I make it so I will always have 2 characters? See my edit above – Skitzafreak Jul 26 '17 at 17:21
  • 2
    Change the format specifier from `x` to `02x` as explained in [this answer](https://stackoverflow.com/a/14678150/1322401) to [python hexadecimal](https://stackoverflow.com/questions/14678132/python-hexadecimal). So `format(3, '02x')` would give you `'03'`. "The `02` part tells `format()` to use at least 2 digits and to use zeros to pad it to length, `x` means lower-case hexadecimal." For your last operation your format would be `"{:02x}{:02x}{:02x}".format(100, 50, 50)` – Steven Rumbalski Jul 26 '17 at 17:25
  • @AshwiniChaudhary [python hexadecimal](https://stackoverflow.com/questions/14678132/python-hexadecimal) is a better duplicate since the OP wants pad single digit results with a leading zero. – Steven Rumbalski Jul 26 '17 at 17:33
  • 1
    @StevenRumbalski Done! – Ashwini Chaudhary Jul 26 '17 at 17:37

1 Answers1

1

try:

val1 = hex(100)[2:]
val2 = hex(50)[2:]
val3 = hex(int(val1, 16) - int(val2, 16))[2:]

hex_str = str(val1) + str(val2) + str(val3)

print(hex_str)
Md. Rezwanul Haque
  • 2,882
  • 7
  • 28
  • 45