moatze
moatze

Reputation: 148

Conversion From String To Int

I'm communicating with a modem via COM port to recieve CSQ values.

response = ser.readline()
csq = response[6:8]

print type(csq)

returns the following:

<type 'str'> and csq is a string with a value from 10-20

For further calculation I try to convert "csq" into an integer, but

i=int(csq)

returns following error:

invalid literal for int() with base 10: ''

Upvotes: 1

Views: 88

Answers (3)

asamarin
asamarin

Reputation: 1594

A slightly more pythonic way:

i = int(csq) if csq else None

Upvotes: 5

frlan
frlan

Reputation: 7260

As alternative you can put your code inside an try-except-block:

try:
    i = int(csq)
except:
    # some magic e.g.
    i = False 

Upvotes: 1

NDevox
NDevox

Reputation: 4086

Your error message shows that you are trying to convert an empty string into an int which would cause problems.

Wrap your code in an if statement to check for empty strings:

if csq:
    i = int(csq)
else:
    i = None

Note that empty objects (empty lists, tuples, sets, strings etc) evaluate to False in Python.

Upvotes: 3

Related Questions