Table of Contents
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
1 2 3 |
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.
1 2 3 4 5 6 7 |
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
1 2 3 4 5 6 7 |
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.
1 2 3 4 5 6 7 8 |
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
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.