Hello coders, In this tutorial you learn how to split string into list in python. There are different technique or methods for splitting python string into list, we will see each one in this tutorial.
- List Typecasting
python programming give us list() function for type casting any python data types into list. You can also used this list() function for splitting python string into list.
def split(words): return list(word) word="programiz" print(split(word))
- Using split() function
You can also used split() function for splitting string into list. This split() function return list of words from string. You can also define separator in split function, the default separator in split() function is black space.
n='7 1 2' l=s.split() print(l)
- List comprehension method
The another technique for converting string to list is by using list comprehension method. By using below syntax you can easily split string into list.
def split("words"): return [char for char in word] word='programiz' print(split(word))
- Using Shlex module
You can also used shlex module for splitting python string to list. Refer the below syntax to split string into list in python.
import shlex w='1 2 3' l=shlex.split(w) print(l)