Python Convert String to List

We can convert a string to list in Python using split() function.

Python String split() function syntax is:

Python Convert String to List

Let’s look at a simple example where we want to convert a string to list of words i.e. split it with the separator as white spaces.

Output: List of Words =['Welcome', 'To', 'JournalDev']

If you are not familiar with f-prefixed string formatting, please read f-strings in Python

If we want to split a string to list based on whitespaces, then we don’t need to provide any separator to the split() function. Also, any leading and trailing whitespaces are trimmed before the string is split into a list of words. So the output will remain same for string s=" Welcome To JournalDev " too.

Let’s look at another example where we have CSV data into a string and we will convert it to the list of items.

Output: List of Items in CSV =['Apple', 'Mango', 'Banana']

Python String to List of Characters

Python String is a sequence of characters. We can convert it to the list of characters using list() built-in function. When converting a string to list of characters, whitespaces are also treated as characters. Also, if there are leading and trailing whitespaces, they are part of the list elements too.

Output: List of Characters =['a', 'b', 'c', '$', ' ', "", ' ', '3', '2', '1', ' ']

If you don’t want the leading and trailing whitespaces to be part of the list, you can use strip() function before converting to the list.

Output: List of Characters =['a', 'b', 'c']

That’s all for converting a string to list in Python programming.

You can checkout complete python script and more Python examples from our GitHub Repository.

By admin

Leave a Reply

%d bloggers like this: