
Python Split String İnto List
1. str.split()
We can use str.split(sep=None)
function which returns a list of the words in the string, using sep
as the delimiter string.
For example, to split the string with delimiter -
, we can do:
1 2 3 | s = ‘1-2-3’ l = s.split(‘-‘) print(l) # prints [‘1’, ‘2’, ‘3’] |
If sep
is not specified or is None
, runs of consecutive whitespace are regarded as a single separator.
1 2 3 | s = ‘1 2 3’ l = s.split() print(l) # prints [‘1’, ‘2’, ‘3’] |
2. shlex.split()
The shlex module defines the shlex.split(s)
function which split the string s
using shell-like syntax.
1 2 3 4 5 | import shlex s = ‘1 2 3’ l = shlex.split(s) print(l) # prints [‘1’, ‘2’, ‘3’] |