Search code examples
attributeerrormicropythonbbc-microbit

bbc-microbit: micropython AttributeError: 'str' object has no attribute 'partition'


On a BBC microbit, I am getting this error and I don't know why:

AttributeError: 'str' object has no attribute 'partition'

when running this code:

uart.write('Received: "' + incoming + '"\n')
head, mid, tail = incoming.partition(' ')

incoming is a string as can be seen in the console

MicroPython v1.9.2-34-gd64154c73 on 2017-09-01; micro:bit v1.0.1 with nRF51822
Type "help()" for more information.
>>> 
>>> Received: "buggy direction 2.16 1.2"
Traceback (most recent call last):
  File "__main__", line 122, in <module>
  File "__main__", line 25, in drive
AttributeError: 'str' object has no attribute 'partition' 

Any ideas what can be done here?


Solution

  • The BBC micropython string class does not have a partition method. Try using the split method. The string "buggy direction 2.16 1.2" in your example has four elements. Trying to split this into just the three variables head, mid, tail will cause an error.

    You can access the first and last element of the string using the example code below:

    words = incoming.split(',')
    head = words[0]
    tail = words[-1]
    print('head: {} tail: {}'.format(head, tail))