str.splitlines() with MicroPython?

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
ZKDMun
Posts: 42
Joined: Thu Nov 24, 2016 2:34 pm
Location: Hamburg

str.splitlines() with MicroPython?

Post by ZKDMun » Sun Jan 22, 2017 2:59 pm

Using Python I can easily split lines by str.splitlines().
But there is no splitline() attribute for MicroPython?

Because after my HTTP GET request I got this "b'\n1000\n999\n" and I want to seperate the two values (in this example "1000" and "999").
Any ideas? :/

User avatar
Roberthh
Posts: 3667
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

Re: str.splitlines() with MicroPython?

Post by Roberthh » Sun Jan 22, 2017 3:42 pm

Code: Select all

[b'\n1000\n999\n'.split(b'\n')
reveals

Code: Select all

[b'', b'1000', b'999', b'']

Naib
Posts: 1
Joined: Sun Jan 22, 2017 4:41 pm

Re: str.splitlines() with MicroPython?

Post by Naib » Sun Jan 22, 2017 4:43 pm

[quote="Roberthh"][code][b'\n1000\n999\n'.split(b'\n')
[/code]reveals
[code][b'', b'1000', b'999', b'']
[/code][/quote]


Yup. As I understand it, micropython does not support UTF-8. Splitlines is a str method

User avatar
dhylands
Posts: 3821
Joined: Mon Jan 06, 2014 6:08 pm
Location: Peachland, BC, Canada
Contact:

Re: str.splitlines() with MicroPython?

Post by dhylands » Mon Jan 23, 2017 1:27 am

Micropython does support utf8.

splitlines seems to work for me.

Code: Select all

>>> 'abc\ndef\nghi'.splitlines()
['abc', 'def', 'ghi']
>>> b'abc\ndef\nghi'.splitlines()
[b'abc', b'def', b'ghi']
If you pass it a string you get strings back (and strings support UTF-8). If you pass it a byte string, you get byte strings back. bytestrings don't support UTF8.

To convert a bytestring to a string use:

Code: Select all

>>> str(b'a>\xc2\xb0<b', 'utf8')
'a>\xb0<b'
>>> bytes('a>\xb0<b', 'utf8')
b'a>\xc2\xb0<b'
>>> print(str(b'a>\xc2\xb0<b', 'utf8'))
a>°<b
>>> 
I'm not sure if the print statement will show up or not. It prints a> followed by a degree symbol followed by <b.

User avatar
Roberthh
Posts: 3667
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

Re: str.splitlines() with MicroPython?

Post by Roberthh » Mon Jan 23, 2017 6:12 am

Whether splitlines is supported depend on the platform. Splitlines works in the Unix and PyBoard version, but not in the esp8266 build. It depends on the setting of MICROPY_PY_BUILTINS_STR_SPLITLINES, which has to be enabled in the build configuration.

SpotlightKid
Posts: 463
Joined: Wed Apr 08, 2015 5:19 am

Re: str.splitlines() with MicroPython?

Post by SpotlightKid » Tue Jan 24, 2017 9:19 am

If you know that your separator is always '\n', there's no reason to use splitlines. Just use split('\n') instead.

Post Reply