27

I'm using Python to script some operations on specific locations in memory (32 bit addresses) in an embedded system.

When I'm converting these addresses to and from strings, integers and hex values a trailing L seems to appear. This can be a real pain, for example the following seemingly harmless code won't work:

int(hex(4220963601))

Or this:

int('0xfb96cb11L',16)

Does anyone know how to avoid this?

So far I've come up with this method to strip the trailing L off of a string, but it doesn't seem very elegant:

if longNum[-1] == "L":
   longNum = longNum[:-1]
C Nielsen
  • 566
  • 1
  • 6
  • 13
  • 3
    Your first example wouldn't work even without the "L" because `int` doesn't know how to handle "0x" prefix. What are you trying to accomplish? – recursive May 06 '11 at 21:33

5 Answers5

24

If you do the conversion to hex using

 "%x" % 4220963601

there will be neither the 0x nor the trailing L.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
13

Calling str() on those values should omit the trailing 'L'.

yan
  • 20,644
  • 3
  • 38
  • 48
  • 14
    Just to let future readers know, yan's answer of calling 'str' on it doesn't work, at least in Python 2.7.3. Str keeps the trailing 'L'. (I don't have enough reputation to comment on Yan's answer) The answers using format or %x do seem to work. – Rhadamanthos Jan 07 '14 at 17:33
  • 2
    broken spacing, but: Python 2.7.5+ (default, Sep 19 2013, 13:48:49) [GCC 4.8.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> n = 123L >>> str(n) '123' >>> str(123L) '123' – yan Jan 07 '14 at 19:42
  • That example is true in general but for hex, hex does not accept strings it returns a string with L in it given an integer :'( – Har Apr 12 '17 at 16:25
3

Consider using rstrip. For example:

result.rstrip("L")
Conor Livingston
  • 905
  • 1
  • 8
  • 17
0

This is what I did: int(variable_which_is_printing_as_123L) and it worked for me. This will work for normal integers.

docpkd
  • 551
  • 9
  • 19
-1

this could help somebody:

>>>n=0xaefa5ba7b32881bf7d18d18e17d3961097548d7cL
>>>print "n=","%0s"%format(n,'x').upper()
n= AEFA5BA7B32881BF7D18D18E17D3961097548D7C
kratenko
  • 7,354
  • 4
  • 36
  • 61