Table of Contents
Working with Strings in Python
In this chapter, you’ll learn how to do useful operations with strings: combining them, repeating them, checking their length, and picking out parts of them.
Assume you already know what a string is and how to store it in a variable (covered in the str chapter).
Throughout this chapter we’ll use examples like:
message = "Hello"
name = "Alice"Concatenation: Joining Strings Together
Concatenation means joining strings end to end.
Use the + operator to concatenate strings:
first_name = "Alice"
last_name = "Smith"
full_name = first_name + last_name
print(full_name) # AliceSmith
full_name_with_space = first_name + " " + last_name
print(full_name_with_space) # Alice SmithYou can concatenate:
- variables that hold strings
- string literals like
" ","!","Python"
Common mistake: trying to add a string and a number directly:
age = 30
# print("Age: " + age) # This causes an error!To fix this, convert the number to a string first (you’ll see more about this when combining text and variables):
age = 30
print("Age: " + str(age)) # Age: 30Repeating Strings with `*`
You can repeat a string multiple times using the * operator with an integer:
laugh = "ha"
print(laugh * 3) # hahaha
line = "-"
print(line * 10) # ----------This is useful for simple text effects:
title = "Python"
print("=" * 10)
print(title)
print("=" * 10)Finding the Length of a String: `len()`
Use len() to count how many characters are in a string:
word = "Python"
print(len(word)) # 6
empty = ""
print(len(empty)) # 0
space = " "
print(len(space)) # 1Remember:
- Spaces, punctuation, and symbols are all counted as characters.
len()returns anint.
Accessing Individual Characters (Indexing)
You can access a single character in a string using square brackets [] with an index.
- Indexing starts at 0.
- For the string
"Python": Pis index0yis index1nis index5
word = "Python"
print(word[0]) # P
print(word[1]) # y
print(word[5]) # nCommon mistakes:
- Using an index that’s too large causes an error:
word = "Hi"
# print(word[2]) # Error: index out of range- Trying to change a character directly:
text = "cat"
# text[0] = "b" # This is NOT allowedStrings are immutable (you can’t change them in place). To “change” them, you build a new string (shown later in this chapter).
Negative Indexing (From the End)
You can also count from the end of the string using negative indices:
-1is the last character-2is the second-to-last, and so on
For "Python":
nis-1ois-2Pis-6
word = "Python"
print(word[-1]) # n
print(word[-2]) # o
print(word[-6]) # PSlicing: Getting Substrings
A slice is a part of a string. Use:
string[start:end]start= index where the slice begins (inclusive)end= index where the slice stops (exclusive, not included)
For "Python":
string[0:2]gives"Py"string[1:4]gives"yth"
Examples:
text = "Python programming"
print(text[0:6]) # Python
print(text[7:18]) # programming
# from index 7 up to (but not including) index 11
print(text[7:11]) # prog
You can omit start or end:
- Omit
start→ slice from the beginning - Omit
end→ slice to the end
text = "Hello, world!"
print(text[:5]) # Hello (from start to index 5, not included)
print(text[7:]) # world! (from index 7 to the end)
print(text[:]) # Hello, world! (whole string)Negative Indices in Slices
You can combine slicing with negative indices:
text = "Hello, world!"
# last 6 characters
print(text[-6:]) # world!
# everything except last character
print(text[:-1]) # Hello, world
# slice using negative start and end
print(text[-6:-1]) # worldBasic String Methods
Strings have methods—functions that belong to the string object.
You call them with dot notation: string.method().
Here are some useful basic methods. They return new strings; they don’t change the original.
Changing Case: `lower()`, `upper()`, `title()`
text = "Hello, World!"
print(text.lower()) # hello, world!
print(text.upper()) # HELLO, WORLD!
print(text.title()) # Hello, World!The original string stays the same:
print(text) # Hello, World!Removing Extra Spaces: `strip()`, `lstrip()`, `rstrip()`
These methods remove spaces (and some other whitespace) from the ends of a string.
raw = " Python "
print("[" + raw + "]") # [ Python ]
print("[" + raw.strip() + "]") # [Python]
print("[" + raw.lstrip() + "]") # [Python ]
print("[" + raw.rstrip() + "]") # [ Python]Counting and Finding Text: `count()`, `find()`
count(sub) tells you how many times a substring appears:
text = "banana"
print(text.count("a")) # 3
print(text.count("na")) # 2
find(sub) gives the index where a substring first appears, or -1 if not found:
text = "Hello, world!"
print(text.find("world")) # 7
print(text.find("Python")) # -1Replacing Text: `replace()`
replace(old, new) returns a new string with all old parts replaced by new:
text = "I like cats. Cats are cute."
new_text = text.replace("cats", "dogs")
print(new_text) # I like dogs. Cats are cute.
new_text2 = text.replace("Cats", "Dogs")
print(new_text2) # I like cats. Dogs are cute.
Note: replacement is case-sensitive ("cats" ≠ "Cats").
Escaping Special Characters
Some characters have a special meaning in strings, like the quote characters and backslash.
Use the backslash \ to escape them.
Quotes Inside Strings
If your string uses double quotes outside, you can use single quotes inside (and vice versa) without escaping:
msg1 = "She said 'hello'."
msg2 = 'He replied "hi".'To use the same quote type inside and outside, escape the inner quotes:
msg = "She said \"hello\"."
print(msg) # She said "hello".New Lines and Tabs: `\n`, `\t`
Some escape sequences represent special characters:
\n→ new line\t→ tab
text = "First line\nSecond line"
print(text)
# First line
# Second line
columns = "Name\tAge"
print(columns)
# Name AgeConverting Between Strings and Numbers (Quick Overview)
When mixing text and numbers, you often need to convert between types:
str(x)→ turnxinto a stringint(s)→ convert stringsto an integer (if possible)float(s)→ convert stringsto a float (if possible)
You’ll use this heavily when combining text and variables, and for user input, but here’s a simple example focused on strings:
age = 25
# Convert number to string to join with +
message = "You are " + str(age) + " years old."
print(message)Simple String Exercises
Try these small tasks to get comfortable with string operations:
- Create a variable
word = "Python"and: - Print the first and last characters.
- Print the substring
"tho"using slicing. - Ask the user (using
input()) for their first and last name, then: - Create a full name with a space between them.
- Print it in uppercase.
- Print how many characters are in the full name (including the space).
- Given
text = " I love Python! ", print: - The text without leading and trailing spaces.
- The number of
"o"characters in the cleaned-up text. - The text with
"Python"replaced by"coding". - Create a simple “banner” for a title:
- Ask for a title (e.g.
"Welcome"). - Print a line of
*characters above and below the title.
The number of*should match the length of the title.
These exercises will give you practice with concatenation, repetition, slicing, string methods, and len().