1
Hatchling0 / 300 XP
0day streak 0stars
Your Python practice
Mock tests Readiness
More
Guest mode · saved on this device.

String methods

Strings come with built-in tools called methods, used with a dot:

s = "  hello WORLD  "
s.strip()        # "hello WORLD"   trim spaces
s.lower()        # "  hello world  "
s.title()        # "  Hello World  "
s.upper()        # "  HELLO WORLD  "
s.replace("l", "L")
"a,b,c".split(",")   # ["a", "b", "c"]

String methods do not change the original string: strings are immutable. Methods such as .strip() return a new string, so store the result. Methods can also be chained: s.strip().title().

s.split() with no argument splits on whitespace and returns a list of words. Lists use indexes just like strings: words[0] is the first item and words[1] the second. len(words) counts the items.

See it run

tag = " ruby "
tag.upper()
shout = tag.upper()
tag = tag.strip()

Strings never change in place. Watch what tag holds after each line.

Practice string methods

Exercise 1

From messy = " hello WORLD " make:

  • clean = "Hello World" (strip + title)
  • shout = clean in upper case
  • words = clean split into a list of words

Exercise 2

People type email addresses sloppily. From raw in the code editor below, make:

  • email = raw with the spaces trimmed and in lower case ("ada.lovelace@example.com")
  • parts = email split at the @
  • username = the first item of parts, domain = the second

Exercise 3

A blog turns post titles into web addresses called slugs. From title in the code editor below, make:

  • slug = trimmed, lower case, with every space replaced by - ("my-first-python-blog-post")
  • word_count = how many words the title has (5)

The check will try a different title too, so build both from title.

Free lesson: use the editor to practice it.

Practice

Loading Python…
More
Loading exercise content…
Visualizer Watch your code run line by line

Run your code, then choose Play to follow its execution.

Memory · names → values
Variables appear here as Python creates them.
Output & plots

One-line daily quest