Strings¶
~15 min ยท prerequisite: Variables and types
What you will be able to do¶
- Write string literals with single, double, and triple quotes, and build text with
+and f-strings. - Read one character with an index, and measure a string with
len. - Use common string methods such as
upper,strip, andreplace, and test whether text contains other text within.
The idea¶
A string is text, and its type is str, which you met in the variables lesson. A string literal is written between quotes, such as "Ada" or 'Ada'. Both forms work. The quotes are not part of the value, and you must close a string with the same kind of quote you used to open it. Triple quotes, """ or ''', let a string run over several lines. Inside a string, the two characters \n stand for a new line, and the two characters \" stand for a double quote.
A string is a sequence, which means its characters are arranged in order. Each character has a position called an index. Counting starts at 0, so "Ada"[0] is "A". A negative index counts from the end, so "Ada"[-1] is "a". Lesson 6 shows how to take several characters at once. For now, use one index at a time.
Strings are immutable, which means you cannot change a character in place. An expression such as word[0] = "J" is an error. To get different text, you make a new string. A method is a function attached to a value and called with a dot and parentheses. Methods such as upper() and replace() return a new string and leave the original unchanged.
Two operators are useful here. The + operator joins two strings, and in checks whether one string appears inside another. The function len returns the number of characters.
An f-string is a string with an f before the opening quote. Any expression inside curly braces is evaluated and inserted into the text. The line f"Hi, {name}" produces Hi, Ada when name holds "Ada". F-strings are usually easier to read than joining pieces with +, and they convert numbers to text for you.
Strings can also be used in a for loop, which visits each character in turn. You learned for in Part 2.
Worked example¶
greeting = "hello, world"
name = "Ada"
print(greeting[0])
print(greeting[-1])
print(len(greeting))
print(greeting.upper())
message = f"Hi, {name}! Your name has {len(name)} letters."
print(message)
Line by line, this is what Python does:
greetingrefers to a string of 12 characters, including the comma and the space.greeting[0]is the first character,h, andprintshows it.greeting[-1]is the last character,d.len(greeting)counts the characters and gives12.greeting.upper()returns a new string with capital letters. The variablegreetingstill holds the lowercase text.- The f-string fills in
nameand the value oflen(name), which is3. The result is stored inmessageand printed.
The output is:
Try it¶
The first block checks indexing and length. The second block checks methods, which return new strings. The third block checks f-strings and a loop over characters.
Common mistakes¶
-
Forgetting the closing quote. Writing
print("Hello)gives:Add the matching quote at the end of the text.
-
Changing a character in place. The code
word = "Python"followed byword[0] = "J"gives:Build a new string instead, such as
"J" + word[1:]. Slicing is covered in lesson 6. -
Indexing past the end. The code
print("abc"[3])gives:A string of length 3 has indexes 0, 1, and 2. Use
lento find the last valid index. -
Adding text and a number. The code
print("Age: " + 17)gives:Convert the number with
str(17), or use an f-string such asf"Age: {17}". -
Forgetting the parentheses on a method. Writing
print(text.upper)shows a description of the method, such as<built-in method upper of str object at ...>, and not the text. Writetext.upper()to call it.
Practice¶
- Create
title = "python basics". Assert thattitle.upper()equals"PYTHON BASICS", and thatlen(title)equals 13. - Create
name = "Ada". Assert thatname[0]is"A"and thatname[-1]is"a". - Create
letter_count = 0. Use aforloop over"banana"and add 1 each time the character is"a". Assert thatletter_countequals 3. - Start with
sentence = "I like dogs". Usereplaceto makenew_sentenceequal to"I like cats". Assert the new value, and assert that the originalsentencedid not change. - Stretch: build
reversed_textby starting with""and, for each character in"stressed", putting that character in front of the text built so far. Assert thatreversed_textequals"desserts".
Solution
-
python title = "python basics" assert title.upper() == "PYTHON BASICS" assert len(title) == 13 -
python name = "Ada" assert name[0] == "A" assert name[-1] == "a" -
python letter_count = 0 for ch in "banana": if ch == "a": letter_count = letter_count + 1 assert letter_count == 3 -
python sentence = "I like dogs" new_sentence = sentence.replace("dogs", "cats") assert new_sentence == "I like cats" assert sentence == "I like dogs" -
python reversed_text = "" for ch in "stressed": reversed_text = ch + reversed_text assert reversed_text == "desserts"
Recap¶
- A string is an immutable sequence of characters. Use
[index]to read one character, andlento count them. - Methods such as
upper,strip, andreplacereturn new strings and leave the original unchanged. - Use f-strings, such as
f"Score: {score}", to put values inside text.