1

I receive from a module a string that is a representation of an long int

>>> str = hex(5L)
>>> str
'0x5L'

What I now want is to convert the string str back to a number (integer)

int(str,16) does not work because of the L.

Is there a way to do this without stripping the last L out of the string? Because it is also possible that the string contains a hex without the L ?

Lohit
  • 126
  • 8
Bart Vanherck
  • 243
  • 2
  • 10

2 Answers2

5

Use str.rstrip; It works for both cases:

>>> int('0x5L'.rstrip('L'),16)
5
>>> int('0x5'.rstrip('L'),16)
5

Or generate the string this way:

>>> s = '{:#x}'.format(5L)  # remove '#' if you don' want '0x'
>>> s
'0x5'
>>> int(s, 16)
5
Ashwini Chaudhary
  • 232,417
  • 55
  • 437
  • 487
2

You could even just use:

>>> str = hex(5L)
>>> long(str,16)
5L
>>> int(long(str,16))
5
>>>
Steve Barnes
  • 26,342
  • 6
  • 60
  • 70