walkingcrane
walkingcrane

Reputation: 73

Invalid literal when using int inside for loop

I have a file with a bunch of streamed hex numbers that I need to convert back to integers. After reading in the data and splitting it into lines, I have the following:

In [153]: text_lines
Out[153]:
['AB01D801AC01870BB6FFE000',
 'A9015F01AB01860B2600B300',
 'A901FE00AC01860BD4FF4E01',
 'AB01E700AB01850B4200DD00',
 'AA017F01AA01850B23009E00',
 'AC017D01AE01840B08004301',
 '']

Now, if I try to iterate through these lines, rearrange the bytes, and convert, I get an error:

In [138]: for line in text_lines:
   .....:     phA.append(int((line[2:4]+line[0:2]),16))
   .....:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-138-eb4d5ccf5005> in <module>()
      1 for line in text_lines:
----> 2     phA.append(int((line[2:4]+line[0:2]),16))
      3

ValueError: invalid literal for int() with base 16: ''

But I can do this with no problem:

In [165]: for i in range(len(text_lines)-1):
   .....:     line = text_lines[i]
   .....:     print int((line[2:4]+line[0:2]),16)
   .....:
427
425
425
427
426
428

I can also break out the first for loop to just display the literal that should be put into the int() function and it looks like just what I expect.

In [174]: for line in text_lines:
   .....:     print line[2:4]+line[0:2]
   .....:
01AB
01A9
01A9
01AB
01AA
01AC

Any ideas as to why iterating over lines within text_lines causes the int() function to break? Thanks.

Upvotes: 0

Views: 126

Answers (2)

Keerthana Prabhakaran
Keerthana Prabhakaran

Reputation: 3787

As Irmen de Jong had mentioned, get rid of your empty string at the end of the list.

A more pythonic way to get rid of your empty string would be, Either by

text_lines=filter(None,text_lines)

Or,
Looping((list comprehension)) with a condition!

>>> [int(line[2:4]+line[0:2],16) for line in text_lines if line]
[427, 425, 425, 427, 426, 428]

Upvotes: 0

Nick is tired
Nick is tired

Reputation: 7055

Your last string is an empty string:

text_lines = ['AB01D801AC01870BB6FFE000',
 'A9015F01AB01860B2600B300',
 'A901FE00AC01860BD4FF4E01',
 'AB01E700AB01850B4200DD00',
 'AA017F01AA01850B23009E00',
 'AC017D01AE01840B08004301',
 ''] # here

And you can't convert empty strings to integers.

You can use filter before your loop to remove the empty string:

>>> text_lines = list(filter(lambda x: x != '', text_lines))
>>> text_lines
['AB01D801AC01870BB6FFE000', 'A9015F01AB01860B2600B300', 'A901FE00AC01860BD4FF4E01', 'AB01E700AB01850B4200DD00', 'AA017F01AA01850B23009E00', 'AC017D01AE01840B08004301']
>>> for line in text_lines:
...     print(int(line[2:4]+line[0:2],16))
...
427
425
425
427
426
428

Upvotes: 1

Related Questions