Module 0 · Functions, Variables · Lesson 3 of 5

Shaping strings

Strings come with built-in methods: functions that belong to the value. You call them with a dot.

  • .strip() removes spaces from both ends
  • .lower(), .upper() change case
  • .title() capitalizes each word; .capitalize() only the first letter
  • .replace(old, new) swaps every old for new
  • .split(" ") cuts a string into pieces

Methods return a new string. You can chain them, reading left to right:

name = input("Name? ").strip().title()

f-strings are the cleanest way to put values inside text. Put an f before the quote and the variable in curly braces:

print(f"hello, {name}")

Users type messy input: extra spaces, odd capitals. Cleaning it with strip and friends is something you'll do in every real program, including the AI apps later in this academy.

Try it

Edit freely · Ctrl+Enter runs

Quick check0 of 3 right

What is " Hi ".strip()?

What is "hello world".title()?

With n = "Noviq", what does f"{n}!" become?

Practice0 of 3 solved

1. Inside voiceTo do

Ask the user for a line of text and print it in all lowercase.

InputOutput
HELLOhello
This Is Pythonthis is python

2. Slow motionTo do

Ask for some text and print it with every space replaced by ..., like someone speaking slowly.

InputOutput
This is PythonThis...is...Python
I love PythonI...love...Python

3. Tidy greetingTo do

Ask for a name that may have extra spaces and odd capitals. Clean it up and print hello, Name using an f-string.

InputOutput
ada LOVELACE hello, Ada Lovelace
gracehello, Grace