String Methods: strip, split, join, replace

The everyday tools for cleaning and reshaping text, each one returning a new string or list.

Python · beginner · 7 min · 8 steps · free

What you'll learn

string_methods.py

line = "  apples, pears, plums  "
clean = line.strip()
parts = clean.split(", ")
joined = " & ".join(parts)
found = clean.find("pears")
has_plum = "plum" in clean
swapped = clean.replace("pears", "figs")
print(parts, joined, found, has_plum, swapped)

Step by step

  1. Messy input: spaces at both ends.
  2. .strip() removes spaces (and newlines) from both ends.
  3. .split(", ") cuts the text at every ", " and gives a list of the pieces.
  4. " & ".join(parts) glues the list back together with " & " between items. The separator comes first.
  5. .find gives the position where "pears" starts: 8. It gives -1 if not found.
  6. in just answers yes or no: True.
  7. .replace swaps every "pears" for "figs" in a new string.
  8. split and join turn text into a list and back; strip, find and replace clean and search. None of them changed line.

Common mistakes

Best practices

Key takeaways

Check yourself

What does "a,b".split(",") give?

Answer: ["a", "b"]. split always returns a list.

What does "cat".find("z") give?

Answer: -1. find returns -1 when the text is not there.

·

More in Python Basics