Python split() and join(): Strings to Lists and Back
Split a String into a List of Words
The split() method cuts a string into pieces and gives you a list of them. With nothing in the brackets, it cuts wherever there are spaces, so you get a list of words.
Think of it like snapping a bar of chocolate along its lines: one bar becomes a row of separate pieces.
sentence = "Sunny likes Python"
words = sentence.split()
print(words)
print(len(words))
print(words[0])['Sunny', 'likes', 'Python'] 3 Sunny
words is an ordinary list from chapter 9, so len(), indexes and slices all work on it.
The rules
split()returns a new list of strings. The original string doesn't change.- With empty brackets, it cuts at spaces, tabs and new lines.
- Extra spaces don't matter: several spaces in a row count as one cut, and spaces at the ends are ignored.
messy = " Rocky and Lucky "
print(messy.split())['Rocky', 'and', 'Lucky']
No empty words, no stray spaces. That makes split() great for text that people type.
Loop over the words
Combine split() with a for loop from chapter 10 to work on each word:
for word in "I love Python".split():
print(word, len(word))I 1 love 4 Python 6
Common beginner doubt: "What's the difference between looping over a string and looping over split()?" Looping over the string gives you characters: I, a space, l, o… Looping over split() gives you words.
text.split()turns a sentence into a list of words.