Skip to content

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, and replace, and test whether text contains other text with in.

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:

  1. greeting refers to a string of 12 characters, including the comma and the space.
  2. greeting[0] is the first character, h, and print shows it.
  3. greeting[-1] is the last character, d.
  4. len(greeting) counts the characters and gives 12.
  5. greeting.upper() returns a new string with capital letters. The variable greeting still holds the lowercase text.
  6. The f-string fills in name and the value of len(name), which is 3. The result is stored in message and printed.

The output is:

h
d
12
HELLO, WORLD
Hi, Ada! Your name has 3 letters.

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.

word = "Python"
assert word[0] == "P"
assert word[-1] == "n"
assert word[1] == "y"
assert len(word) == 6
text = "  Hello World  "
clean = text.strip()
assert clean == "Hello World"
assert text == "  Hello World  "
assert clean.lower() == "hello world"
assert clean.replace("World", "Python") == "Hello Python"
assert "World" in clean
assert "Moon" not in clean
score = 7
line = f"Score: {score}"
assert line == "Score: 7"

letters = ""
for ch in "abc":
    letters = letters + ch.upper()
assert letters == "ABC"
assert "one\ntwo".count("\n") == 1

Common mistakes

  1. Forgetting the closing quote. Writing print("Hello) gives:

    SyntaxError: unterminated string literal (detected at line 1)
    

    Add the matching quote at the end of the text.

  2. Changing a character in place. The code word = "Python" followed by word[0] = "J" gives:

    TypeError: 'str' object does not support item assignment
    

    Build a new string instead, such as "J" + word[1:]. Slicing is covered in lesson 6.

  3. Indexing past the end. The code print("abc"[3]) gives:

    IndexError: string index out of range
    

    A string of length 3 has indexes 0, 1, and 2. Use len to find the last valid index.

  4. Adding text and a number. The code print("Age: " + 17) gives:

    TypeError: can only concatenate str (not "int") to str
    

    Convert the number with str(17), or use an f-string such as f"Age: {17}".

  5. 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. Write text.upper() to call it.

Practice

  1. Create title = "python basics". Assert that title.upper() equals "PYTHON BASICS", and that len(title) equals 13.
  2. Create name = "Ada". Assert that name[0] is "A" and that name[-1] is "a".
  3. Create letter_count = 0. Use a for loop over "banana" and add 1 each time the character is "a". Assert that letter_count equals 3.
  4. Start with sentence = "I like dogs". Use replace to make new_sentence equal to "I like cats". Assert the new value, and assert that the original sentence did not change.
  5. Stretch: build reversed_text by starting with "" and, for each character in "stressed", putting that character in front of the text built so far. Assert that reversed_text equals "desserts".
Solution
  1. python title = "python basics" assert title.upper() == "PYTHON BASICS" assert len(title) == 13

  2. python name = "Ada" assert name[0] == "A" assert name[-1] == "a"

  3. python letter_count = 0 for ch in "banana": if ch == "a": letter_count = letter_count + 1 assert letter_count == 3

  4. python sentence = "I like dogs" new_sentence = sentence.replace("dogs", "cats") assert new_sentence == "I like cats" assert sentence == "I like dogs"

  5. 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, and len to count them.
  • Methods such as upper, strip, and replace return new strings and leave the original unchanged.
  • Use f-strings, such as f"Score: {score}", to put values inside text.

Sources