7. Python Strings
What you will learn
- How to write strings and use escapes
- Indexing and slicing
- The most useful string methods
- Formatting with f-strings
Writing strings
Use single or double quotes, and triple quotes for text over several lines.
Python code
a = "She said 'hi'"
b = 'It is "great"'
c = """Line one
Line two"""
print(a)
print(b)
print(c)
Output
She said 'hi' It is "great" Line one Line two
Escapes use a backslash: \n new line, \t tab, \\ backslash, and \" a quote. A raw string such as r"C:\new\folder" keeps backslashes as typed.
Length and indexing
Positions start at 0. Negative numbers count from the end.
Python code
word = "Python"
print(len(word))
print(word[0])
print(word[-1])
Output
6 P n
Slicing
text[start:stop] takes characters from start up to, but not including, stop.
Python code
word = "Python"
print(word[0:2])
print(word[2:])
print(word[:3])
print(word[-3:])
print(word[::-1])
Output
Py thon Pyt hon nohtyP
Leaving a side empty means “from the start” or “to the end”. [::-1] reverses the string.
Strings cannot be changed in place
Python code: this fails
word = "cat"
word[0] = "b"
What Python reports
TypeError: 'str' object does not support item assignment
Build a new string instead, for example "b" + word[1:].
Useful methods
| Method | Does |
|---|---|
upper(), lower(), title() |
Change case |
strip() |
Remove spaces from both ends |
replace(old, new) |
Replace every match |
find(text) |
Position of the first match, or -1 |
startswith(t), endswith(t) |
Check the beginning or end |
split(sep) |
Turn a string into a list |
join(list) |
Join a list into a string |
count(text) |
How many times it appears |
Python code
text = " Learn Python Today "
clean = text.strip()
print(clean.upper())
print(clean.lower())
print(clean.replace("Today", "Daily"))
print(clean.find("Python"))
print("Python" in clean)
print(clean.startswith("Learn"))
print(clean.count("o"))
Output
LEARN PYTHON TODAY learn python today Learn Python Daily 6 True True 2
The word in checks whether one string is inside another.
Splitting and joining
Python code
tags = "html,css,python"
parts = tags.split(",")
print(parts)
print(len(parts))
print(" | ".join(parts))
Output
['html', 'css', 'python'] 3 html | css | python
Formatting with f-strings
Python code
name = "Sam"
score = 7
price = 1234.5
print(f"{name} scored {score} points")
print(f"Price: {price:,.2f}")
print(f"{score:03d}")
print(f"{0.256:.1%}")
print(f"{name:>8}|")
Output
Sam scored 7 points
Price: 1,234.50
007
25.6%
Sam|
,.2fadds thousands separators and two decimals.03dpads a whole number with zeros to 3 digits..1%shows a percentage.>8right-aligns in a width of 8.
Comparing strings
Comparison is case sensitive. To ignore case, compare lowercased copies.
Python code
print("Apple" == "apple")
print("Apple".lower() == "apple".lower())
Output
False True
Looping through a string
Python code
for letter in "abc":
print(letter)
Output
a b c
Common mistakes
- Forgetting that methods return a new string, so the result must be stored.
- Counting positions from 1.
- Trying to change a character with an index.
- Joining a string and a number with
+. - Building SQL or web addresses by joining visitor text, which is unsafe.
Exercise
Given email = " Sam@Example.com ", clean it (strip and lower case), print it, and print whether it contains an @.
Show solution
email = " Sam@Example.com "
clean = email.strip().lower()
print(clean)
print("@" in clean)
Output: sam@example.com then True
Knowledge check
1. What does "Python"[-1] give?
"n", the last character.
2. Which method turns a string into a list?
split()
3. Can you change a string with word[0] = "b"?
No. Strings are immutable.
Summary
- Strings support indexing, slicing, and many methods that return new strings.
- Use
split,join,strip,replace, andin. - F-strings format text and numbers clearly.