Pathwise

Intro to Python · Lesson 3 of 12 · 12 min

Strings: working with text

Text in Python is a string, a row of characters in quotes. Join strings, measure them, pick out characters by position, and build sentences with f-strings.

STRINGS

Text lives between quotes

A string is a row of characters inside quotes. Single or double quotes both work, as long as they match: "Sara" and 'Sara' are the same string. Anything in quotes is text, even digits, so "5" is the character 5, not the number five. Letters, spaces, punctuation and Persian text are all characters.

"5" + "5" gives "55", because joining two pieces of text just puts them side by side.

first = "Sara"
last = "Karimi"
print(first + " " + last)
print("ha" * 3)
print(len("Python"))

Output

Sara Karimi
hahaha
6

+ joins strings end to end, so the space between the names has to be added yourself. * repeats a string. len() counts the characters: Python has 6. Spaces count too, so len("hi there") is 8.

Check yourself

print("ab" * 3)
  1. ababab
  2. ab3
  3. ab ab ab
  4. abab
Show the answer
ababab

INDEXING

Every character has a position, starting at 0

Square brackets after a string pick one character by its position, its index. Counting starts at 0, so in word = "Python", word[0] is P and word[5] is n. Negative positions count back from the end: word[-1] is always the last character. Asking for a position that isn't there, like word[6], stops with IndexError: string index out of range.

Python has 6 characters, so its positions run 0 to 5, one less than its length.

Check yourself

word = "Python"
print(word[0] + word[-1])
  1. Pn
  2. Py
  3. Po
  4. nP
Show the answer
Pn

Step through it

  1. word = "Python": six cells in a row

    The string "Python" is drawn as six cells side by side, one character in each, with the name word on the left. That's all a string is: characters kept in order, each in its own place.

  2. Every cell gets a position number

    Under the cells are their positions, 0 to 5: counting starts at 0, so the sixth character, n, is at 5. The dimmer row above counts back from the end, from -6 at P to -1 at n.

  3. word[0] is P and word[-1] is n

    Square brackets pick one character by its position. The arrow word[0] points down at the first cell, P, and word[-1] at the last cell, n; both cells light up.

  4. word[0:3] takes cells 0 to 2: "Pyt"

    A bracket runs under cells 0, 1 and 2, labelled word[0:3], with an arrow to "Pyt". The orange line stands at position 3, where the slice stops: the start is included and the end isn't, so the h at 3 is left out.

Check yourself

What is "Python"[0:3]?

  1. Pyt
  2. Pyth
  3. yth
  4. Py
Show the answer

Pyt

Right. A slice starts at the first number and stops just before the second, so it takes positions 0, 1 and 2: P, y and t.

word = "Python"
print(word[2:])
print("sara".upper())
print("  hi  ".strip())
print("a-b".replace("-", "+"))

Output

thon
SARA
hi
a+b

Leave out the end of a slice and it runs to the end of the string: word[2:] is thon. Methods are actions a string can do, written after a dot: upper() makes capitals, strip() removes spaces at both ends, and replace() swaps one piece of text for another. Each one hands back a new string.

name = "Omid"
age = 30
print(f"{name} is {age}")
print(f"Next year: {age + 1}")

Output

Omid is 30
Next year: 31

An f-string has an f right before the opening quote. Anything inside curly braces is worked out and dropped into the text, numbers included, so you don't have to convert or join anything yourself. This is the easy way to mix text and numbers.

Check yourself

  1. age = 30
  2. print("Age: " + age)
Show the answer

The bug is on line 2.

Found it. + can join two strings, but age is a number, so Python stops with TypeError: can only concatenate str (not "int") to str. Write print(f"Age: {age}"), or turn the number into text with str(age).

Check yourself

With word = "Python", word[6] gives the last letter, n.

Show the answer

False

False. Positions start at 0, so the six letters sit at 0 to 5, and there is nothing at 6: it stops with an IndexError. The last letter is word[5], or more simply word[-1].

Lesson recap

  • A string is text in single or double quotes; "5" is text, not a number.
  • + joins strings (add spaces yourself), * repeats them, and len() counts characters, spaces included.
  • Positions start at 0 and [-1] is the last character; a position past the end is an IndexError.
  • A slice like word[0:3] includes the start and stops before the end; methods like upper() return a new string.
  • f-strings such as f"{name} is {age}" mix text and numbers; "Age: " + 30 is a TypeError.

Keep it, don't just read it

Pathwise brings each idea back just before you'd forget it, with a quick question. Free on Android and on the web, in English and Persian.

Cafe Bazaar Myket Open the web app

All lessons in this course

  1. Your first program
  2. Variables: names for values
  3. Strings: working with text
  4. Input and types
  5. Making decisions with if
  6. Lists: many values in one place
  7. Loops: doing it again
  8. Functions: name a job, reuse it
  9. Dictionaries: look it up by name
  10. Reading error messages
  11. Saving and reading files
  12. Final project: an expense tracker