What You Will Learn
Strings are one of the most used types in Python. This lesson covers the most useful things you can do with them.
String Length
len() returns the number of characters in a string:
name = "Alice"
print(len(name))
city = "New York"
print(len(city))
Expected output:
5
8
Spaces count as characters.
Accessing Characters
Each character in a string has a position (called an index). Indexing starts at 0:
name = "Alice"
print(name[0]) # A
print(name[1]) # l
print(name[4]) # e
Expected output:
A
l
e
Negative indexes count from the end:
print(name[-1]) # e (last character)
print(name[-2]) # c (second to last)
Slicing
Extract a portion of a string with [start:end]:
text = "Hello, world!"
print(text[0:5]) # Hello
print(text[7:12]) # world
print(text[:5]) # Hello (start defaults to 0)
print(text[7:]) # world! (end defaults to the end)
Expected output:
Hello
world
Hello
world!
Common String Methods
Methods are functions that belong to a string. Call them with a dot:
Changing Case
name = "alice"
print(name.upper()) # ALICE
print(name.capitalize()) # Alice
print(name.title()) # Alice
name2 = "HELLO"
print(name2.lower()) # hello
Removing Whitespace
messy = " hello "
print(messy.strip()) # "hello"
print(messy.lstrip()) # "hello "
print(messy.rstrip()) # " hello"
Checking Content
email = "user@example.com"
print(email.startswith("user")) # True
print(email.endswith(".com")) # True
print("@" in email) # True
print("example" in email) # True
Replacing Text
sentence = "I like cats"
new = sentence.replace("cats", "dogs")
print(new)
Expected output:
I like dogs
Splitting
csv = "Alice,Bob,Carol,Dave"
names = csv.split(",")
print(names)
Expected output:
['Alice', 'Bob', 'Carol', 'Dave']
split() breaks a string into a list (you will learn about lists in a later lesson).
f-strings — The Best Way to Format Strings
f-strings let you embed variables directly inside a string:
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
Expected output:
My name is Alice and I am 25 years old.
Put f before the opening quote, then wrap variable names in {}. This is much cleaner than concatenating strings with +.
What You Learned
len()returns the length of a string- Use
[index]to access individual characters - Use
[start:end]to slice a portion of a string - Common methods:
.upper(),.lower(),.strip(),.replace(),.split() - f-strings are the best way to embed variables in text
In the next lesson, you will learn how to get input from the user so your programs can interact with people.