livepython.net
CHAPTER 12Working With Strings
12.3  SPLIT AND JOIN

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.

PYTHONedit me
sentence = "Sunny likes Python"
words = sentence.split()
print(words)
print(len(words))
print(words[0])
OUTPUT
['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.
PYTHONedit me
messy = "  Rocky   and  Lucky "
print(messy.split())
OUTPUT
['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:

PYTHONedit me
for word in "I love Python".split():
    print(word, len(word))
OUTPUT
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.

your turnPredict the output

What will this print?

print(len("one two three".split()))
Your turn! What will this code show on the screen?
your turnType the output

Type what this prints

words = "red green blue".split() print(words[-1])
Read the code line by line, then type the output exactly.

Split on a Comma or Another Separator

Put a separator in the brackets, and split() cuts exactly at that text instead of at spaces: text.split(","). The separator itself disappears.

Think of it like a train ticket with perforated lines: you tear exactly along the dotted lines, nowhere else.

PYTHONedit me
data = "Sunny,25,Pune"
parts = data.split(",")
print(parts)
print(parts[2])
OUTPUT
['Sunny', '25', 'Pune']
Pune

The rules

  • split(sep) cuts exactly at sep and keeps everything else, spaces included.
  • Two separators in a row give an empty string: "a,,b".split(",") gives ['a', '', 'b'].
  • The pieces are always strings, even when they look like numbers.

Watch the spaces after the commas here:

PYTHONedit me
fruits = "apple, banana, mango"
print(fruits.split(","))
print(fruits.split(", "))
OUTPUT
['apple', ' banana', ' mango']
['apple', 'banana', 'mango']

Split on ", " (a comma and a space), or strip() each piece afterwards.

Many numbers on one line

People often type several numbers on one line. Split the line, then convert each piece with int() inside a loop:

PYTHONedit me
line = input()
total = 0
for part in line.split():
    total += int(part)
print("Total:", total)
OUTPUT
Total: 60

Avoid: adding the pieces without converting

PYTHONedit me
total = 0
for part in "10 20".split():
    total += part
print(total)
OUTPUT
TypeError: unsupported operand type(s) for +=: 'int' and 'str'

Don't be scared of this error! It's saying you tried to add text to a number. "10" is still a string after split(), so convert it with int(part).

Common beginner doubt: "Why is '25' in quotes in the list?" Because split() only cuts text. It never guesses that a piece is a number.

split(",") cuts at every comma, and the pieces are always strings.

your turnFill the gap

Get the year from the date

date = "15-08-1947" parts = date.split(?) print(parts[2])

It should print: 1947

Which piece makes this code work?
your turnPredict the output

Remember adding up in a loop?

total = 0 for n in [2, 4, 6]: total += n print(total)
Your turn! What will this code show on the screen?

Join a List into a String with join()

The join() method does the opposite of split(): it glues a list of strings into one string. You write the separator first, then .join() with the list: " ".join(words).

Think of it like threading beads on a necklace: the beads are the words, and the separator is the little knot you tie between each pair.

PYTHONedit me
names = ["Sunny", "Rocky", "Lucky"]
print(" ".join(names))
print(", ".join(names))
print("-".join(names))
print("".join(names))
OUTPUT
Sunny Rocky Lucky
Sunny, Rocky, Lucky
Sunny-Rocky-Lucky
SunnyRockyLucky

The rules

  • The separator goes in front: separator.join(list).
  • The separator goes only between items, never at the start or the end.
  • Every item in the list must be a string.
  • An empty separator "" glues the items with nothing in between.

Avoid: joining numbers

PYTHONedit me
nums = [1, 2, 3]
print("-".join(nums))
OUTPUT
TypeError: sequence item 0: expected str instance, int found

"Sequence item 0" is the first item of the list. It's an int, and join() only accepts strings.

Good: turn each number into text first

Build a new list of strings with a loop and str(), then join it:

PYTHONedit me
nums = [1, 2, 3]
parts = []
for n in nums:
    parts.append(str(n))
print("-".join(parts))
OUTPUT
1-2-3

Common beginner doubt: "Why is it " ".join(words) and not words.join(" ")?" Because join() is a string method: it belongs to the separator. Lists don't have a join() method at all, and Python tells you so.

separator.join(list) glues strings together with the separator between them.

your turnSpot the bug

Which line breaks?

One line stops this program. Tap it.
your turnPredict the output

What will this print?

print("+".join(["1", "2", "3"]))
Your turn! What will this code show on the screen?

Split, Change, Join: Edit Every Word

Most text tasks follow one pattern: split the text into a list, change each piece, then join the pieces back together. Once you know it, you can edit every word of a sentence.

Think of it like a toy train: take the carriages apart, paint each one, then couple them back together.

The pattern

  1. Split the text into a list of words.
  2. Change each word in a loop, and append() the new word to a new list.
  3. Join the new list into one string.
PYTHONedit me
sentence = "Sunny likes tea"
new_words = []
for word in sentence.split():
    new_words.append(word[::-1])
print(" ".join(new_words))
OUTPUT
ynnuS sekil aet

Each word is reversed with the slice [::-1] from topic 1, but the words stay in their places.

A web address from a title

Websites turn a title into a slug: small letters, dashes instead of spaces. Here lower() changes every word at once, so no loop is needed:

PYTHONedit me
title = "My First Python Program"
words = title.lower().split()
print("-".join(words))
OUTPUT
my-first-python-program

This very page has a slug like that in its address.

Clean up extra spaces in one line

split() ignores extra spaces, and join() puts back exactly one. Together they tidy any messy text:

PYTHONedit me
messy = "  too    many   spaces "
print(" ".join(messy.split()))
OUTPUT
too many spaces

Common beginner doubt: "Why build a new list instead of changing the words in place?" Each word is a string, and strings can't change. So you make new words and collect them in a new list.

Split, change each piece, then join: the pattern behind most text tasks.

your turnOrder the lines

Put the lines in order to print: learn-python-fast

  1. slug = "-".join(words)
  2. print(slug)
  3. title = "Learn Python Fast"
  4. words = title.lower().split()
These lines are mixed up. Put them back in order, then press Check.
your turnPredict the output

What will this print?

print(" ".join("a b c".split()))
Your turn! What will this code show on the screen?

Practice: Split and join

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 105.Python Program to Count the Words in a SentenceEasySolve
  2. 106.Python Program to Reverse the Words in a SentenceMediumSolve