Python Strings
Master string methods, slicing, f-strings, concatenation, and escape characters in Python.
Creating and Concatenating Strings
A string is a sequence of characters enclosed in quotes. You can use single quotes 'hello' or double quotes "hello". Concatenation means joining strings together using the + operator.
# Creating strings
greeting = "Hello"
name = 'Alice'
# Concatenation (joining strings)
message = greeting + ", " + name + "!"
print(message)
# f-strings (formatted string literals) - the modern way
age = 16
print(f"My name is {name} and I am {age} years old.")
print(f"Next year I will be {age + 1}.")
Hello, Alice!My name is Alice and I am 16 years old.Next year I will be 17.
String Slicing and Indexing
Every character in a string has a position called an index. In Python, indexing starts at 0. You can extract parts of a string using slicing with the syntax string[start:end].
word = "Python" # P y t h o n # Index: 0 1 2 3 4 5 print(word[0]) # First character: P print(word[-1]) # Last character: n print(word[0:3]) # Characters 0, 1, 2: Pyt print(word[2:]) # From index 2 to end: thon print(word[:4]) # From start to index 3: Pyth print(len(word)) # Length of string: 6
String Methods and Escape Characters
Python strings come with many built-in methods (functions attached to the string). Escape characters start with a backslash \ and represent special characters.
text = " Hello, World! "
# Common string methods
print(text.strip()) # Remove whitespace: "Hello, World!"
print(text.lower()) # Lowercase: " hello, world! "
print(text.upper()) # Uppercase: " HELLO, WORLD! "
print(text.replace("World", "Python")) # Replace text
print("hello".count("l")) # Count occurrences: 2
print("hello".find("ll")) # Find position: 2
# Escape characters
print("She said \"Hi!\"") # \" for quotes inside quotes
print("Line 1\nLine 2") # \n for new line
print("Column1\tColumn2") # \t for tab
Key Vocabulary
Concatenation
Joining two or more strings together using the + operator.
f-string
A formatted string literal f"..." that lets you embed expressions inside {}.
Slicing
Extracting a portion of a string using string[start:end] syntax.
Escape Character
A special character starting with \ such as \n (newline) or \t (tab).
Worked Examples
Format a student report using f-strings
name = "Olivia"
subject = "Mathematics"
score = 87.5
report = f"Student: {name}\nSubject: {subject}\nScore: {score}%"
print(report)
print(f"Grade: {'Distinction' if score >= 85 else 'Credit'}")
Step 1: We store the student's details in variables.
Step 2: The f-string lets us embed variables directly inside {} and use \n for line breaks.
Output: Student: Olivia | Subject: Mathematics | Score: 87.5% | Grade: Distinction
Extract initials from a full name using slicing
full_name = "Sarah Jane Smith"
parts = full_name.split() # Split into a list: ["Sarah", "Jane", "Smith"]
first_initial = parts[0][0] # "S"
middle_initial = parts[1][0] # "J"
last_initial = parts[2][0] # "S"
initials = first_initial + middle_initial + last_initial
print(f"Initials: {initials}") # Initials: SJS
Step 1: split() breaks the string into a list of words.
Step 2: We use [0] on each word to get the first character, then concatenate them.
Clean and format user input
raw_email = " [email protected] " # Clean the email clean_email = raw_email.strip().lower() print(f"Cleaned email: {clean_email}") # Check the domain domain = clean_email.split("@")[1] print(f"Domain: {domain}") print(f"Is Gmail? {domain == 'gmail.com'}")
Step 1: strip() removes whitespace, and lower() converts to lowercase.
Step 2: We split at @ and take the second part [1] to get the domain.
Output: Cleaned email: [email protected] | Domain: example.com | Is Gmail? False
Knowledge Check
Select the correct answer for each question. Click "Check Answer" to see if you are right.
Question 1
What does "Python"[1] return?
Question 2
What does "HELLO".lower() return?
Question 3
Given name = "Alice", what does f"Hi {name}!" produce?
Question 4
What does "Hello World"[0:5] return?
Question 5
What escape character creates a new line?
Key Concepts Summary
-
●
Strings can be created with single or double quotes and joined with
+. -
●
f-strings (
f"...") let you embed variables and expressions inside curly braces. -
●
String indexing starts at 0. Use slicing
[start:end]to extract substrings. -
●
Common methods:
.upper(),.lower(),.strip(),.split(),.replace(). -
●
Escape characters:
\n(newline),\t(tab),\"(quote).