🐍

String Manipulation

Beginner
80 XP
35 min
Lesson Content

Strings: Working with Text

Strings are sequences of characters. Python provides powerful tools for manipulating and working with text data.

String Basics

# Single or double quotes
name = "Alice"
name = 'Alice'  # Same thing

# Multi-line strings message = """This is a multi-line string"""
# Escape characters quote = "She said \"Hello\"" # She said "Hello"
newline = "Line 1\nLine 2" # Two lines

String Concatenation

# Using + operator
first = "Hello"
last = "World"
greeting = first + " " + last # "Hello World"
# Using f-strings (recommended)
name = "Alice"
age = 25
message = f"My name is {name} and I'm {age} years old"

String Methods

Python has many built-in string methods:

text = "  Hello World  "

# Case conversion
print(text.upper()) # " HELLO WORLD "
print(text.lower()) # " hello world "
print(text.title()) # " Hello World "
print(text.capitalize()) # " hello world "
# Stripping whitespace
print(text.strip()) # "Hello World" (removes spaces)
print(text.lstrip()) # "Hello World " (left only)
print(text.rstrip()) # " Hello World" (right only)
# Finding and replacing
text = "Hello World"
print(text.find("World")) # 6 (index where found)
print(text.replace("World", "Python")) # "Hello Python"
# Checking content
print(text.startswith("Hello")) # True
print(text.endswith("World")) # True
print("Hello" in text) # True

String Indexing and Slicing

text = "Python"

# Access characters by index
print(text[0]) # P (first character)
print(text[-1]) # n (last character)
# Slicing
print(text[0:3]) # Pyt (characters 0, 1, 2)
print(text[:3]) # Pyt (from start to index 3)
print(text[3:]) # hon (from index 3 to end)
print(text[::-1]) # nohtyP (reverse)

String Formatting

name = "Alice"
age = 25
# f-strings (Python 3.6+, recommended)
message = f"Name: {name}, Age: {age}"
# .format() method
message = "Name: {}, Age: {}".format(name, age)
message = "Name: {0}, Age: {1}".format(name, age)
# % formatting (older style)
message = "Name: %s, Age: %d" % (name, age)

String Operations

text = "Hello World"

# Get length
print(len(text)) # 11
# Count occurrences
print(text.count("l")) # 3
# Split into list
words = text.split() # ["Hello", "World"]
words = text.split("l") # ["He", "o Wor", "d"]
# Join list into string
words = ["Hello", "World"]
text = " ".join(words) # "Hello World"

Common String Patterns

# Check if string is numeric
text = "123"
print(text.isdigit()) # True
# Check if alphabetic
text = "Hello"
print(text.isalpha()) # True
# Check if alphanumeric
text = "Hello123"
print(text.isalnum()) # True
Example Code

Practice string manipulation methods.

# Process a text string
text = "  python programming  "

# 1. Remove whitespace and convert to title case
text = text.strip().title()
print(text)

# 2. Replace 'programming' with 'coding'
text = text.replace("Programming", "Coding")
print(text)

# 3. Check if it contains 'Python'
print("Contains 'Python':", "Python" in text)

Expected Output:

Python Programming
Python Coding
Contains 'Python': True
Study Tips
  • Read the theory content thoroughly before practicing
  • Review the example code to understand key concepts
  • Proceed to the Practice tab when you're ready to code