Python

Lesson 3 of 10

Lesson ยท 10 min

Working with text

Strings have methods

A string is a piece of text, and every string comes with methods. A method is a function that belongs to a value. You write the value, a dot, and the method name.

city = "lisbon"
print(city.upper())   # LISBON
print(city.title())   # Lisbon

A string method never changes the string. It gives you a new string. If you want to keep the new string, put it in a variable.

Methods you will use often

Code Result
" hi ".strip() "hi"
"Hello".lower() "hello"
"hello".upper() "HELLO"
"a quick fox".title() "A Quick Fox"
"a-b-c".split("-") ["a", "b", "c"]
"red fox".replace("red", "grey") "grey fox"
"hello".startswith("he") True

split() with nothing in the parentheses splits at spaces, and it ignores extra spaces. It returns a list. You will learn about lists in lesson 6.

Length, positions, and slices

word = "python"
print(len(word))     # 6
print(word[0])       # p
print(word[-1])      # n  (the last character)
print(word[1:4])     # yth  (from position 1 up to, but not including, 4)

in checks whether a piece of text is inside another one:

print("th" in word)  # True

Your turn

The variable message is already in the editor. It has extra spaces at both ends. Write your code under it.

Tasks

5 to do

  1. Task 1, not checked yet. Make a variable clean that holds message without the spaces at the start and the end. Use the strip method.

  2. Task 2, not checked yet. Make a variable title that holds clean with a capital letter at the start of every word. Use the title method.

  3. Task 3, not checked yet. Make a variable words that holds the words of clean as a list. Use the split method. Then make a variable count with the number of words. Use len.

  4. Task 4, not checked yet. Make a variable dashed that holds clean with every space changed to a hyphen -. Use the replace method.

  5. Task 5, not checked yet. Print the first word of the list in capital letters. Use the upper method. The output is THE.

Task 1 of 5

Make a variable clean that holds message without the spaces at the start and the end. Use the strip method.

All tasks

main.py

Ctrl+Enter runs your code. Ctrl+Shift+Enter checks it. Press Esc, then Tab, to leave the editor.

Output

Press Run to see your result

Your output shows here. Press Run to try your code.