Lesson 2 of 10

Strings and their methods

Goal

Clean up text and slice it

01

Explanation

A string is a sequence of characters, and each character has a position number starting from zero: date[0] is the first character and date[-1] is the last. You can take part of a string with slicing: date[:4] gives you the first four characters and date[-2:] the last two. Note that the start position is included in the slice and the end position is not.

Most text is typed by people, so it comes with stray spaces and a mix of upper and lower case. That's why strings have built-in methods you call after a dot: strip() removes spaces from both ends, lower() and upper() convert letters to lower or upper case, replace(a, b) swaps one piece of text for another, split() breaks the string into a list of words, and "-".join(words) joins words into one string with the separator of your choice between them.

Remember that a string can't be changed. If you write title.lower() on a line by itself, title stays exactly as it was, because the method returns a new string that you need to store in a variable. Also note that split() with empty parentheses ignores repeated spaces, while split(" ") gives you empty strings between them.

02

Your task

Turn title into a slug, the readable part of a page's URL: all lower case, with a hyphen between words, so it becomes "learn-python-fast". Then use slicing to take year (the first four characters) and day (the last two) from date.

Checks

5 checks
  1. slug is all lower case
  2. slug has no spaces
  3. Words are separated by a single hyphen
  4. year is the first four characters of date
  5. day is the last two characters of date
03

Hints

0/3
Track lessons0 of 10 done

Start with the most beginner-friendly language there is, and use it to learn variables, strings, lists, conditions, loops and functions.

Beginner level, 10 lessons, 2 hours in total.

main.py
OutputPython (Pyodide)

Loading Python. This only happens once. Your browser keeps it after that.

–/5

Checks start once the environment is ready.

5 checks listed under “Your task”.

Track lessons0 of 10 done

Start with the most beginner-friendly language there is, and use it to learn variables, strings, lists, conditions, loops and functions.

Beginner level, 10 lessons, 2 hours in total.