Split a string into a list--help needed

Questions and discussion about running MicroPython on a micro:bit board.
Target audience: MicroPython users with a micro:bit.
Post Reply
MicroGuy
Posts: 17
Joined: Sun Jan 17, 2021 8:31 pm

Split a string into a list--help needed

Post by MicroGuy » Fri Jul 02, 2021 6:03 pm

I want to take a numeric value such as -9.472, convert it to a string (OK, I can do that), and then convert the string into a list:
my_list, which equals [ "-", "9", ".", and so on. The individual characters will get used on a display. I found the statement below in the online documentation:

String.split(separator: str, limit: number): List[str]

But the "explanation" doesn't include a concrete example of how to use this statement. Can someone help, please? Thanks.

Also, I could not find information about how to interpret the statement above. It might help to have an introduction to the docs that describes this syntax. Cheers. --Jon

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

Re: Split a string into a list--help needed

Post by dhylands » Fri Jul 02, 2021 6:09 pm

You don't really need to split the string into a list. You can just dereference the characters from the string directly.

Code: Select all

>>> s = '-9.4732'
>>> s[0]
'-'
>>> s[1]
'9'
>>> s[2]
'.'
>>> len(s)
7
>>> for ch in s:
...     print(ch)
... 
-
9
.
4
7
3
2
>>> for idx in range(len(s)):
...     print(s[idx])
... 
-
9
.
4
7
3
2

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

Re: Split a string into a list--help needed

Post by Roberthh » Fri Jul 02, 2021 6:29 pm

If you really want a list my_list mad from a string str, you can simply write:

my_list = list(str)

But, as Dave said, direct dereferencing the str is the shortcut you most probably should take.

MicroGuy
Posts: 17
Joined: Sun Jan 17, 2021 8:31 pm

Re: Split a string into a list--help needed

Post by MicroGuy » Fri Jul 02, 2021 7:18 pm

Fantastic guys! Didn't know that was possible. I greatly appreciate your help. Happy 4th of July. --Jon

Post Reply