07 - Strings
Strings represent text. They are ordered sequences of characters and are immutable.
A simple picture
A string is like a train made of character carriages:
"Python"
0 1 2 3 4 5 <- positions called indexes
P y t h o n
You can inspect a carriage or build a new train, but you cannot replace one carriage inside the existing string.
Creating strings
single = 'Python'
double = "Python"
multi_line = """This text
uses more than one line."""
Choose consistent quotes. Use escaping when a string contains the same quote character:
message = "He said, \"Learn Python.\""
Indexing
An index is the numbered position of one character. Indexes start at zero:
word = "Python"
print(word[0]) # P
print(word[2]) # t
print(word[-1]) # n
word[6] raises IndexError because the last valid index is 5.
Slicing
A slice copies a selected part of a string. text[start:stop:step] stops before stop:
word = "Python"
print(word[0:2]) # Py
print(word[2:]) # thon
print(word[:4]) # Pyth
print(word[::2]) # Pto
print(word[::-1]) # nohtyP
Immutability
You cannot replace one character in place:
word = "cat"
# word[0] = "b" # TypeError
word = "b" + word[1:]
print(word) # bat
String methods return a new string:
name = " ravi sharma "
clean_name = name.strip().title()
print(clean_name) # Ravi Sharma
Important fact: string methods do not change the original string. Save the returned string when you need it.
name = " maya "
name.strip()
print(name) # The spaces are still present.
clean_name = name.strip()
print(clean_name) # maya
Useful string methods
| Method | Purpose | Example |
|---|---|---|
.lower() |
lowercase | text.lower() |
.upper() |
uppercase | text.upper() |
.title() |
title case | name.title() |
.strip() |
remove outer whitespace | text.strip() |
.replace(a, b) |
replace text | text.replace("old", "new") |
.split() |
create a list of words | sentence.split() |
.join(items) |
combine strings | ", ".join(names) |
.startswith() |
check beginning | code.startswith("PY") |
.endswith() |
check ending | file.endswith(".py") |
.find() |
find index or -1 |
text.find("py") |
.split() returns a group called a list, and .join() combines a group of strings. Lists are taught fully in the next chapter.
Searching and counting
sentence = "Python makes problem solving easier"
print("Python" in sentence) # True
print(sentence.lower().count("p"))
Use .casefold() instead of .lower() when building more language-aware case-insensitive comparisons.
Real-world example: clean a username
raw_username = input("Username: ")
username = raw_username.strip().lower()
if len(username) >= 5 and username.isalnum():
print("Username accepted")
else:
print("Use at least five letters or digits")
Common mistakes
- Forgetting that indexes begin at zero.
- Assuming the slice stop index is included.
- Calling
.strip()and expecting it to remove all internal spaces. - Trying to modify a character directly.
- Comparing text without deciding whether case should matter.
Bug Hunter
Bug 1 — index outside the string
word = "cat"
print(word[3])
Bug 2 — immutable string
word = "cat"
word[0] = "b"
print(word)
Bug 3 — returned value ignored
name = " maya "
name.strip()
print(name)
Show Bug Hunter fixes
# Bug 1: valid indexes are 0, 1, and 2.
print(word[2])
# Bug 2: build a new string.
word = "b" + word[1:]
# Bug 3: save the new string.
name = name.strip()
Optional deeper look: text and memory
Python strings store Unicode text and are immutable. Unicode allows one program to represent many writing systems and symbols. Because a string cannot change in place, operations such as slicing, replacing, or joining produce a new string object. Repeatedly joining thousands of pieces with + can be slower than collecting them and using .join() once.
Practice
Try these problems on this page. Decide first whether spaces and letter case should matter.
Problems
- Count characters in a sentence, excluding spaces.
- Reverse a string using slicing.
- Check whether a word is a palindrome.
- Count vowels and consonants.
- Normalize a person’s name.
- Replace repeated spaces with one space.
- Count the words in a sentence.
- Find the first occurrence of a target word.
- Challenge: check whether two words are anagrams after learning
sorted()and lists in Chapter 08. - Validate a username using length and allowed characters.
Show hints
- Remove spaces or count only characters that are not spaces.
- Use a slice with a step of
-1. - Compare the word with its reverse.
- Normalize to lowercase and check membership in
"aeiou". - Use
strip()andtitle(). - Use
split()andjoin(). split()creates a list of words.- Use
find()orin. - Normalize both words and compare their sorted characters.
- Combine length and allowed-character checks.
Show solution ideas
len(sentence.replace(" ", ""))handles ordinary spaces.text[::-1].word == word[::-1]after applying the chosen normalization.- Loop through the text and increment the correct counter.
name.strip().title().' '.join(text.split()).len(sentence.split()).sentence.lower().find(target.lower()).- Compare
sorted(left.lower())andsorted(right.lower()). - Check length, letters/digits, and any extra username rules.
Homework
Build a text analyzer that reports character count, word count, vowel count, and the longest word in a sentence.
Checkpoint
Write a program that normalizes a sentence by removing outer spaces, converting it to lowercase, and counting its non-space characters.