Split a string into a Python list
This post will discuss how to split a delimited and non-delimited string into a list in Python.
Related Post:
1. Using list() constructor
The list() constructor builds a list directly from an iterable, and since the string is iterable, you can construct a list from it by passing the string to the list constructor:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': input = 'ABC' chars = list(input) print(chars) # ['A', 'B', 'C'] |
2. Using str.split() function
You can use the 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 -, you can do:
|
1 2 3 4 5 6 |
if __name__ == '__main__': s = '1-2-3' l = s.split('-') print(l) # prints ['1', '2', '3'] |
If sep is not specified or is None, consecutive whitespace runs are regarded as a single separator.
|
1 2 3 4 5 6 |
if __name__ == '__main__': s = '1 2 3' l = s.split() print(l) # prints ['1', '2', '3'] |
3. Using shlex.split() function
The shlex module defines the shlex.split(s) function, which split the string s using shell-like syntax.
|
1 2 3 4 5 6 7 8 |
import shlex if __name__ == '__main__': s = '1 2 3' l = shlex.split(s) print(l) # prints ['1', '2', '3'] |
That’s all about splitting a string into a list in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)