Page 1 of 1

Split a string into a list--help needed

Posted: Fri Jul 02, 2021 6:03 pm
by MicroGuy
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

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

Posted: Fri Jul 02, 2021 6:09 pm
by dhylands
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

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

Posted: Fri Jul 02, 2021 6:29 pm
by Roberthh
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.

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

Posted: Fri Jul 02, 2021 7:18 pm
by MicroGuy
Fantastic guys! Didn't know that was possible. I greatly appreciate your help. Happy 4th of July. --Jon