Variables & Data Lesson 8 of 23
Python Strings and f-strings
Create strings with quotes, use escape characters and multi-line strings, join and repeat text, get characters by index, slice strings, and format with f-strings.
Text is everywhere in programs: names, messages, labels, files. In Python, text is a string (str), and Python has excellent tools for working with it.
Creating strings
a = "double quotes"
b = 'single quotes'
c = "It's easy" # apostrophe inside double quotes
d = 'She said "Kaya!"' # double quotes inside single quotes
Escape characters
print("Line 1\nLine 2") # \n = new line
print("Name:\tAna") # \t = tab
print("It\'s a \"test\"") # escaped quotes
print("C:\\Users\\Ana") # \\ = one backslash
Output
Line 1 Line 2 Name: Ana It's a "test" C:\Users\Ana
Multi-line strings
receipt = """
TINDAHAN NI ALING NENA
----------------------
Pandesal x10 ₱25.00
Kape x2 ₱16.00
"""
print(receipt)
Joining and repeating
first = "Andres"
last = "Bonifacio"
print(first + " " + last)
print("ha" * 3)
print("-" * 20)
Output
Andres Bonifacio hahaha --------------------
Length
print(len("Pilipinas"))
Output
9
Indexing: one character
Each character has a position, starting at 0. Negative numbers count from the end:
P i l i p i n a s
0 1 2 3 4 5 6 7 8
-9 -8 -7 -6 -5 -4 -3 -2 -1
word = "Pilipinas"
print(word[0])
print(word[4])
print(word[-1])
Output
P p s
Slicing: part of a string
word[start:end] gives the characters from start up to, but not including, end:
word = "Pilipinas"
print(word[0:4]) # first 4 characters
print(word[4:]) # from index 4 to the end
print(word[:3]) # first 3
print(word[-3:]) # last 3
print(word[::-1]) # reversed!
Output
Pili pinas Pil nas sanipiliP
Strings can't be changed
word = "hello"
word[0] = "H"
Error
TypeError: 'str' object does not support item assignment
Strings are immutable. Make a new string instead: word = "H" + word[1:].
f-strings in detail
An f-string (formatted string) starts with f and fills in anything inside { }:
name = "Gabriela"
grade = 9
avg = 92.3456
print(f"Name: {name}")
print(f"Grade {grade} → Grade {grade + 1} next year")
print(f"Average: {avg:.2f}")
print(f"{name.upper()}")
print(f"|{name:<12}|{grade:>4}|") # left and right align
Output
Name: Gabriela Grade 9 → Grade 10 next year Average: 92.35 GABRIELA |Gabriela | 9|
Alignment is perfect for printing tables: < left, > right, ^ center, followed by the width.
Checking content with in
section = "Grade 10 - Rizal"
print("Rizal" in section)
print("Luna" not in section)
Output
True True
Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04