String Operations
Manipulating Text in Python
In the previous unit, we explored Python's built-in functions. Now let's look at strings, one of the most common data types you'll work with.

Creating Strings
Python treats single quotes and double quotes the same way.
str1 = "Hello"
str2 = 'World'
For text that spans multiple lines, use triple quotes:
text = """
Four score and seven years ago our fathers brought forth on this continent,
a new nation, conceived in Liberty, and dedicated to the proposition that all
men are created equal.
"""
Everything between the triple quotes, including newlines, becomes part of the string.
Combining and Repeating
The + operator concatenates strings:
greeting = "Hello"
name = "Alice"
message = greeting + ", " + name + "!"
print(message) # Outputs: Hello, Alice!
The * operator repeats a string:
laugh = "ha" * 5
print(laugh) # Outputs: hahahahaha
String Methods
Python provides built-in methods for transforming strings. Here are the ones you'll use most.
text = "Hello, World!"
print(text.lower()) # "hello, world!"
print(text.upper()) # "HELLO, WORLD!"
print(text.split(",")) # ['Hello', ' World!']
print(text.replace("World", "Python")) # "Hello, Python!"
lower() and upper() change case. split() breaks a string into a list at the specified character. replace() swaps one substring for another.
Formatting with f-strings
F-strings let you embed variables directly inside string literals. Put an f before the opening quote and wrap variables in curly braces.
name = "Alice"
print(f"Hello, {name}!") # Outputs: Hello, Alice!
Python also has an older format() method:
print("Hello, {}!".format(name)) # Outputs: Hello, Alice!
F-strings are cleaner and more readable, so prefer them for new code.
Project: Text Analysis
Let's use string operations to analyze the Gettysburg Address. We'll count words, find specific terms, and locate the longest word.
text = """
Four score and seven years ago our fathers brought forth on this continent,
a new nation, conceived in Liberty, and dedicated to the proposition that all
men are created equal.
Now we are engaged in a great civil war, testing whether that nation, or any
nation so conceived and so dedicated, can long endure. We are met on a great
battlefield of that war. We have come to dedicate a portion of that field, as
a final resting place for those who here gave their lives that that nation
might live. It is altogether fitting and proper that we should do this.
"""
# Convert to lowercase for consistent counting
text = text.lower()
# Count sentences
num_sentences = text.count(".")
print(f"Sentences: {num_sentences}")
# Remove punctuation and split into words
clean_text = text.replace(",", "").replace(".", "")
words = clean_text.split()
# Count total words
print(f"Words: {len(words)}")
# Count a specific word
word = "nation"
print(f"'{word}' appears {words.count(word)} times")
# Find the longest word
longest = max(words, key=len)
print(f"Longest word: {longest}")
The program converts everything to lowercase so "Nation" and "nation" count as the same word. We remove punctuation with replace(), then split on whitespace to get a list of words. The max() function with key=len finds the longest string in the list.
Try modifying this to analyze different texts. Count unique words, find the most common word, or calculate average word length.
In the next unit, we'll explore lists and learn how to store and manipulate collections of values.