Lesson 4: Working with Strings

How Python handles text, formatting, slicing, and useful string operations

What Are Strings?

Strings represent text in Python. They are created using quotes:

message = "Hello, world!"
name = 'Alice'

String Concatenation

You can combine strings using the + operator:

first = "Hello"
second = "Python"
result = first + " " + second
print(result)   # Hello Python

String Length

Use len() to get the number of characters:

text = "Python"
print(len(text))   # 6

String Indexing and Slicing

Strings behave like sequences, so you can access characters by index:

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

Slicing extracts parts of a string:

print(word[0:3])   # Pyt
print(word[2:])    # thon
print(word[:4])    # Pyth

Common String Methods

Python includes many built‑in string methods:

text = "  hello world  "

print(text.upper())      # HELLO WORLD
print(text.lower())      # hello world
print(text.strip())      # hello world
print(text.replace("world", "Python"))  # hello Python

Finding Substrings

sentence = "Python is awesome"
print(sentence.find("is"))   # 7
print(sentence.find("Java")) # -1 (not found)

String Formatting

Python offers several ways to format strings.

f‑strings (recommended)

name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")

format() method

print("My name is {} and I am {} years old.".format(name, age))

Multiline Strings

Use triple quotes for multi-line text:

message = """This is
a multi-line
string."""

Next Steps

Now that you understand how to work with strings, you’re ready to explore Python’s core data structures in Lesson 5: Lists, Tuples, and Dictionaries.

← Back to Lesson Index