Lesson 6 of 12
Working with Strings 🔠
What You'll Learn
- Concatenate strings
- Use f-strings for easy formatting
- Use common string methods
String Concatenation
You can join strings together with +:
Python
first = "Hello" last = "Oklahoma" greeting = first + ", " + last + "!" print(greeting) # Hello, Oklahoma!
F-Strings (The Easy Way!)
f-strings let you insert variables directly into a string. Just put an f before the quote and wrap variable names in curly braces:
Python
name = "Jordan"
age = 12
print(f"Hi {name}! You are {age} years old.")
print(f"Next year you will be {age + 1}.")F-Strings Are Best
Most Python programmers prefer f-strings over + concatenation because they are cleaner and easier to read.
Useful String Methods
Python
text = "hello, oklahoma!"
print(text.upper()) # HELLO, OKLAHOMA!
print(text.capitalize()) # Hello, oklahoma!
print(len(text)) # 17 (number of characters)
print(text.replace("hello", "hi")) # hi, oklahoma!Name Card Generator
Ask for first name, last name, and city. Print a formatted "name card" using an f-string like: Hello! My name is [Full Name] and I am from [City].
Quick Check
How do you insert a variable into an f-string?
What does .upper() do to a string?
What does len('Hello') return?