Lesson 3.9 – Operating with Strings (PCEP Objective 3.4)

What we’ll learn today

  • How to create and work with strings
  • Indexing and slicing
  • Immutability of strings
  • Escape characters and quoting
  • Multi-line strings
  • Basic string functions and methods

Quick Review

  • What is the difference between a list and a tuple?
  • Are strings mutable or immutable?

Constructing Strings

s1 = "Hello"
s2 = 'World'
print(s1, s2)

Quotes and Apostrophes

print("I'm learning Python")
print('She said "Hi!" to me')

Escape Characters

  • Use \ for special characters
print("First line\nSecond line")
print("He said: \"Python is fun!\"")

Multi-line Strings

poem = """Roses are red,
Violets are blue."""
print(poem)

Indexing and Slicing

word = "Python"
print(word[0])    # P
print(word[-1])   # n
print(word[0:3])  # Pyt

Strings are Immutable

text = "hello"
# text[0] = "H"   ❌ Error
text = "H" + text[1:]
print(text)       # Hello

Basic String Functions

msg = "Python"
print(len(msg))        # 6
print(min(msg))        # 'P'
print(max(msg))        # 'y'

Basic String Methods

s = "hello world"
print(s.upper())     # HELLO WORLD
print(s.lower())     # hello world
print(s.find("world"))   # 6
print(s.replace("world", "Python"))

Class Question

  • Why can’t we just assign to a character in a string like we do with lists?

Mini Practice

  1. Create a string with your name.
  2. Print the first and last letters.
  3. Print the string in all uppercase.

Mini Challenge

  • Write a program that:
    1. Creates the string "I love programming"
    2. Prints it in lowercase
    3. Replaces programming with Python
    4. Prints the result