In this post, we will see how to convert String to list in Python.
We can use String’s split function to convert String to list.
String’s split function
Python String split function signature
str.split(sep=None, maxsplit=-1)
Parameters
sep: A string parameter that will be used as a separator.
maxsplit: Number of times split
Let’s see some examples.
Using split without any parameter
if we don’t provide any separator, string will be splitted by space by default.
str = "Hello world from Java2blog"
# call split function
list1=str.split()
print(str)
print('List of words: ',list1)
Output:
Hello world from Java2blog
List of words: [‘Hello’, ‘world’, ‘from’, ‘Java2blog’]
List of words: [‘Hello’, ‘world’, ‘from’, ‘Java2blog’]
Using split with separator comma
str = "India,China,Nepal,Bhutan"
# call split function
listOfCountries=str.split(',')
print(str)
print('List of countries:',listOfCountries)
Output:
India,China,Nepal,Bhutan
List of countries: [‘India’, ‘China’, ‘Nepal’, ‘Bhutan’]
List of countries: [‘India’, ‘China’, ‘Nepal’, ‘Bhutan’]
Convert string to list of characters
We can convert string to list of characters using list function.
str = "Hello world"
# call split function
list1=list(str)
print(str)
print('List of words: ',list1)
print(str1)
Output:
Hello world
List of words: [‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘w’, ‘o’, ‘r’, ‘l’, ‘d’]
List of words: [‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘w’, ‘o’, ‘r’, ‘l’, ‘d’]
That’s all about how to convert string to list python