Sikau

Python · Day 2 · about 30 min

Strings and f-strings

Slicing, string methods and formatted output.

Most data is text

Names, addresses, CSV files, web pages, log lines, messages — most real-world data arrives as text. Python is famous for how pleasant it makes text work: slicing with one bracket expression, dozens of built-in string methods, and f-strings that format a receipt line in one go.

A string (type str) is a sequence of Unicode characters, so "नमस्ते" and "momo 🥟" are ordinary strings. Single and double quotes mean the same thing; triple quotes ("""…""") let a string span several lines.

Indexing and slicing

Strings are sequences, so s[0] is the first character and s[-1] the last — negative indexes count from the end. slicing takes a piece: s[start:stop] includes start but not stop. Leave out start or stop to go from the beginning or to the end, and add a step for every n-th character. s[::-1] is the classic reversed copy.

city = "Pokhara"
print(city[0], city[-1])
print(city[0:3], city[3:])
print(city[::2], city[::-1])
print(len(city), "kha" in city)

Strings are immutable: you can't change a character in place (city[0] = "p" is a TypeError). Every method returns a new string, so remember to keep the result: name = name.strip().

The rest of this lesson

  • Methods and f-stringsexplain
  • Slices of Kathmandupredict
  • Clean up a messy nameorder
  • Join and splitfill
  • Text toolswrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 10 lessons of Python