Reputation: 11
I am reading a message from serial. It is working fine.
If I use this code, it works
while 1:
data_raw=ser.read(33).decode('ascii')
if len(data_raw) > 0:
print(data_raw[0])
OUTPUT
===== RESTART: C:\Users\...=====
S
S
S
S
S
But if I use this code, it doesn't work
while 1:
data_raw=ser.read(33).decode('ascii')
if data_raw[0] is 'S':
print(data_raw[0])
OUTPUT
if data_raw[0] is 'S':
IndexError: string index out of range
Upvotes: 0
Views: 83
Reputation: 1088
In the first case, you properly check the length of the data_raw
list before accessing any item of it.
Whereas, in your second item you test a condition on the first item of data_raw if data_raw[0] is 'S':
but you have to make sure this item is actually defined.
Here, Python tells you there is no data_raw[0]
. You need to make sure len(data_raw) > 0
before accessing data_raw[0]
.
Upvotes: 2