In this tutorial, we will discuss the methods to split a string into a list.
Python string has split() method it can be used to split the string into a list.
Syntax
str.split(sep=None, maxsplit=-1)
Parameters
- seperator – seperator used to split the string, it can be a character or multiple characters (optional)
- maxsplit – Number of splits to do, maxsplit+1 elements in the output list (optional)
Returns a list of words in the string.
Examples
Simple split example
# string to split
message = "welcome to python programming examples"
word_list = message.split()
print(word_list)
Output
['welcome', 'to', 'python', 'programming', 'examples']
Character separator
pro_langs = "cpp,python,java,,go,kotlin,php"
#Comma as seperator
lang_list = pro_langs.split(",")
print(lang_list)
Output
['cpp', 'python', 'java', '', 'go', 'kotlin', 'php']
Multiple characters as a separator
nums = "100<>201<>300<>404<>203<>300"
#"<>" as seperator
numbers = nums.split("<>")
print(numbers)
Output
[‘100’, ‘201’, ‘300’, ‘404’, ‘203’, ‘300’]
Using max split parameter
pro_langs = "cpp,python,java,,go,kotlin,php"
lang_list = pro_langs.split(",", 2)
print(lang_list)
Output
['cpp', 'python', 'java,,go,kotlin,php']
From the above output, we got max_split+1(3) elements in the list.
Convert a string to a list of characters in Python
Method 1: To convert a string into a list of characters we can use a list constructor.
txt = "World"
chrs = list(txt)
print(chrs)
Output
[‘W’, ‘o’, ‘r’, ‘l’, ‘d’]
Method 2: Using list comprehension.
txt = "World"
chrs = list(txt)
print(chrs)
Output
[‘W’, ‘o’, ‘r’, ‘l’, ‘d’]
Conclusion
It is easy to split strings into a list in python using the split function. You can read about list append vs extend function performance here.