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
Task 1, not checked yet. Make a variable
cleanthat holdsmessagewithout the spaces at the start and the end. Use thestripmethod.Task 2, not checked yet. Make a variable
titlethat holdscleanwith a capital letter at the start of every word. Use thetitlemethod.Task 3, not checked yet. Make a variable
wordsthat holds the words ofcleanas a list. Use thesplitmethod. Then make a variablecountwith the number of words. Uselen.Task 4, not checked yet. Make a variable
dashedthat holdscleanwith every space changed to a hyphen-. Use thereplacemethod.Task 5, not checked yet. Print the first word of the list in capital letters. Use the
uppermethod. The output isTHE.
Task 1 of 5
Make a variable clean that holds message without the spaces at the start and the end. Use the strip method.