Python String split() Method

From time to time, you will find yourself trying to get a list of things from a string. For this purpose, you can use the split() function.

How to use Python split function

The first split function parameter is a separator, character on which the division of string will be happening. If the split function has an empty separator character, whitespace will be used as default splitting character. Let’s look at the example:

s = 'And now something completely different...'
print(s.split())
# ['And', 'now', 'something', 'completely', 'different...']

We can use also custom string as splitting string:

s = 'spam, ham, sausages, spam, sausage - spam, spam with eggs'
print(s.split(", "))
# ['spam', 'ham', 'sausages', 'spam', 'sausage - spam', 'spam with eggs']

What I personally consider the greatest plus of Python split method is actually a possibility to directly assign split string parts into the variable. Here is a nice example:

s = 'spam, ham, eggs'
x, y, z = s.split(", ")
print(x)
# spam
print(y)
# ham
print(z)
# eggs

Splitting the string is opposite of concatenation. If you want to concatenate the strings, check the guide how to concatenate the strings in the best way.

This entry was posted in Language basics and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.