Python, how to create a list from a string

By

Learn how to create a list from a string in Python using the split() method, passing the separator like a space to break the string into a list of words.

~~~

To create a list from a string in Python, use the split() method that every string provides. It cuts the string wherever it finds the separator you pass, and returns a list of the pieces.

First you need to decide how to cut the string. For example, every time there is a space:

phrase = 'I am going to buy the milk'
words = phrase.split(' ')

print(words)
# ['I', 'am', 'going', 'to', 'buy', 'the', 'milk']

The original string is not modified. split() returns a new list.

Splitting on other separators

Any string works as a separator. A comma is a common one, for example when you receive data in a CSV-like format:

groceries = 'milk,bread,eggs'
items = groceries.split(',')

print(items)
# ['milk', 'bread', 'eggs']

Watch out for multiple spaces

Here’s a pitfall. If you split on ' ' and the string contains two or more spaces in a row, you get empty strings in the result:

print('I  am   here'.split(' '))
# ['I', '', 'am', '', '', 'here']

That happens because there is an empty piece between two consecutive separators.

The fix is to call split() with no arguments at all. In that case Python splits on any run of whitespace, including tabs and newlines, and skips the empty pieces:

print('I  am   here'.split())
# ['I', 'am', 'here']

This is what I use when I want the words of a sentence, because I don’t have to trust the input to be perfectly formatted.

Limiting the number of splits

You can pass a second argument, maxsplit, to stop after a number of cuts:

phrase = 'I am going to buy the milk'
print(phrase.split(' ', 2))
# ['I', 'am', 'going to buy the milk']

The rest of the string stays together as the last element. Handy when you only care about the first word or two.

Getting a list of characters

If what you want is a list of the single characters, split() is not the tool. Pass the string to list() instead:

print(list('milk'))
# ['m', 'i', 'l', 'k']

Every character becomes an element, spaces included.

Tagged: Python · All topics
~~~

Related posts about python: