Python Strings
1. Indexing & Length (Recap)
- Access characters by index:
s[0]→ first character - Negative indexes work too:
s[-1]→ last character - Get length:
len(s)
2. String Methods
.count()
Counts how many times a character/substring appears.
s = "hello"
s.count("l") # → 2
.find()
Returns the index of the first occurrence of a character. Returns -1 if not found (does not raise an error).
s.find("l") # → 2
s.find("a") # → -1
Guide: Unlike
.index()on lists (which raises an error if not found),.find()safely returns-1.
.upper() / .lower()
Convert a string to all uppercase or all lowercase.
s.upper() # → "HELLO"
s.lower() # → "hello"
Practical use: Normalize user input before comparing.
if answer.lower() == "tim":
print("Correct!")
.capitalize()
Capitalizes only the first letter of the string.
"algo expert".capitalize() # → "Algo expert"
.isdigit()
Returns True if the string represents a valid integer, False otherwise.
"19".isdigit() # → True
"19h".isdigit() # → False
"19.4".isdigit() # → False (floats return False)
Practical use: Validate user input before converting to int.
num = input("Number: ")
if num.isdigit():
num = int(num)
print(num + 5)
else:
print("Not an int")
.split(delimiter)
Splits a string into a list of substrings using a delimiter. Default delimiter is a space.
"hello my name is Tim".split() # → ['hello', 'my', 'name', 'is', 'Tim']
"hello,my,name".split(",") # → ['hello', 'my', 'name']
"hello,,name".split(",") # → ['hello', '', 'name'] ← empty string between commas
.replace(old, new)
Replaces all occurrences of a substring with a new one. Returns a new string (original is unchanged).
s = "a,b,c"
s2 = s.replace(",", "|") # → "a|b|c"
# s is still "a,b,c"
.join(iterable)
Builds a string from a list/tuple by joining elements with a separator.
lst = ["T", "i", "m"]
"".join(lst) # → "Tim"
"-".join(lst) # → "T-i-m"
"|".join(lst) # → "T|i|m"
3. The in Operator
Check whether a character or substring exists in a string.
"h" in "hello" # → True
"z" in "hello" # → False
4. F-Strings (Python 3.6+)
Embed variables or expressions directly inside a string using {}.
name = "Tim"
s = f"Hello, {name}!" # → "Hello, Tim!"
s = f"1 + 4 = {1 + 4}" # → "1 + 4 = 5"
- Start with
forFbefore the opening quote. - Use
{}to embed any Python expression — no manual conversion needed. - Can be used directly inside
print():
print(f"Hello, {name}!")
5. String Multiplication
Repeat a string by multiplying it with an integer.
"Tim" * 3 # → "TimTimTim"
6. Multi-line Strings
Use triple quotes (""" or ''') to span a string across multiple lines.
s = """Hello,
my name is Tim,
and this is a multi-line string!"""
Guide: Without assignment, triple quotes act as a multi-line comment.
7. Escape Characters
Use a backslash \ to include a quote character inside a string that uses the same quote type.
s = 'Tim\'s code' # → Tim's code
s = "She said \"hi\""
Tip: Avoid escaping by mixing quote types:
s = "Tim's code" # single quote inside double-quoted string — no escape needed
Cheat Sheet Table
| Method | What it does |
|---|---|
s[i] / s[-1] |
Index access / negative index |
len(s) |
Length of string |
s.count(x) |
Count occurrences of x |
s.find(x) |
Index of first x, or -1 |
s.upper() |
All uppercase |
s.lower() |
All lowercase |
s.capitalize() |
First letter uppercase |
s.isdigit() |
Is the string a valid integer? |
s.split(delim) |
Split into list by delimiter |
s.replace(a, b) |
Replace all a with b |
sep.join(lst) |
Join list into string |
x in s |
Check membership |
f"...{expr}..." |
F-string: embed expressions |
s * n |
Repeat string n times |