Danny
Danny

Reputation: 158

Python string parsing

I have just started with Python and I am having trouble parsing strings. I am very much a newbie and I am just playing around with the basics for now. I thought I'd start with parsing trivial stuff like the output of pi_info() just to get some practice with text parsing.

Here is my script:

import gpiozero

boardinfo_length = None
counter = 1

boardinfo = gpiozero.pi_info()
for value in boardinfo:
 if counter != 15:
 print('[', end=' ')
 print(counter, end=' ')
 print(']', end=' ')
 print(boardinfo_length, end=' ')
 print(value)
 print()
else:
 print('[', end=' ')
 print(counter, end=' ')
 print(']', end=' ')
 split_string = value.split(":")
 for split_string_value in split_string:
 print(split_string_value)
 counter += 1

Here is the output:

[ 1 ] None a02082

[ 2 ] None 3B

[ 3 ] None 1.2

[ 4 ] None 2016Q1

[ 5 ] None BCM2837

[ 6 ] None Sony

[ 7 ] None 1024

[ 8 ] None MicroSD

[ 9 ] None 4

[ 10 ] None 1

[ 11 ] None True

[ 12 ] None True

[ 13 ] None 1

[ 14 ] None 1

[ 15 ] Traceback (most recent call last):
File "boardinfo.py", line 19, in <module>
split_string = value.split(":")
AttributeError: 'dict' object has no attribute 'split'

Can someone help me figure it out ...

Upvotes: 0

Views: 661

Answers (1)

PnkFlffyUncrn
PnkFlffyUncrn

Reputation: 133

The type of the last value is a dictionary, not a string. Since dicts don't have the split()-method, i probably would check the type of value first:

for value in boardinfo:
    if isinstance(value, str):
        # String handling
    elif isinstance(value, dict):
        print("This is a dictionary: " + str(value))
    else:
        print("value has type: " + str(type(value)))

Upvotes: 1

Related Questions