Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 3.2 — The String Methods You Use Daily
Python · Example 1 of 3

Trim, split, join and replace

Look at the quotes in the output: repr makes invisible spaces and newlines visible.

A method is a built-in action attached to a value, called with a dot: text.strip(). Strings have dozens, and about twenty cover almost everything: trimming, splitting and joining, replacing, searching, changing case, removing prefixes, and checking what a string contains.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Take name = " Ada Lovelace ". Make a clean lowercase version in clean, print it with repr, then print it in title case.

02

Turn the line "name,age,city" into name | age | city using split and join.

03

Given f = "photo.JPG", check that it is a JPEG regardless of case, and print its name without the extension.

Explain it without notes

01

Why does text.upper() on its own line not change text?

02

What is the difference between find and index, and between strip("ab") and removeprefix("ab")?

03

How do split and join relate, and what is special about split() with no argument?

04

When would you choose partition over split?

Trim, split, join and replace
Sign in to run this example in your browser.

Expected output

'   Hello, World!  \n'
'Hello, World!'
'Hello, World!  \n'
'   Hello, World!'
'hi'
['apple', 'banana', 'cherry']
how many: 3
['a', 'b', 'c']
['a', 'b', 'c,d']
apple + banana + cherry
Python
a+b+c
bbaa