Sitemap
Geek Culture

A new tech publication by Start it up (https://medium.com/swlh).

Member-only story

Split a String Into a List in Python

2 min readJul 31, 2021

--

Photo by Alex Chumak on Unsplash

Split a Single String Into a List

We can make a list of strings from a single string using the split method:

str.split(sep=None, maxsplit=-1)

str is the string that will be split or used to create the list. sep is the delimiter string. maxsplit is the maximum number of splits needed (so the list will have at most maxsplit+1 elements). If maxsplit is not specified (meaning it is the default value of -1), there is no limit on the number of splits.

list_of_words = 'Hello I am a test'.split(' ')print(list_of_words)
# ['Hello', 'I', 'am', 'a', 'test']

Note how the delimiter used is just a space since that is what we want to split the string on.

list_of_words = 'Hello-I-am-a-test'.split('-')print(list_of_words)
# ['Hello', 'I', 'am', 'a', 'test']

If we specify maxsplit to be 3, then the rest of the string is returned as the last element in the list after the maximum number of splits is achieved:

list_of_words = 'Hello-I-am-a-test'.split('-', 3)print(list_of_words)
# ['Hello', 'I', 'am', 'a-test']

--

--

Luay Matalka
Luay Matalka

Written by Luay Matalka

Lead Machine Learning Engineer, specializing in MLOps, with a passion for teaching.