Python Strings
🐍 Python Strings
A string in Python is a sequence of characters enclosed in:
-
"double quotes" -
'single quotes' -
'''triple single quotes'''(multi-line) -
"""triple double quotes"""(multi-line)
✅ Creating Strings
📌 String Indexing
Strings are indexed, meaning each character has a position:
Example:
🔄 String Slicing
You can extract parts of a string:
🏗️ Modifying Strings
Strings are immutable, but we can create new strings using built-in methods.
| Method | Description | Example |
|---|---|---|
upper() |
Convert to UPPERCASE | "hello".upper() |
lower() |
Convert to lowercase | "HELLO".lower() |
title() |
Each word Capitalized | "python tutorial".title() |
capitalize() |
First letter uppercase | "hello world".capitalize() |
strip() |
Remove spaces | " hello ".strip() |
replace() |
Replace text | "Hello".replace("H", "J") |
Example:
🔍 Searching Strings
| Method | Purpose |
|---|---|
find() |
Returns index of substring (or -1 if not found) |
count() |
Counts occurrences |
startswith() |
Checks beginning |
endswith() |
Checks ending |
Example:
🧩 Concatenation (+) & Repeating (*)
🧵 String Formatting (Very Important)
1️⃣ f-strings (Best and Recommended)
2️⃣ format() method
3️⃣ % formatting (old style)
🔠 String Escape Characters
| Escape | Meaning |
|---|---|
\" |
Double quote inside string |
\' |
Single quote |
\\ |
Backslash |
\n |
New line |
\t |
Tab |
Example:
🧪 String Methods Full List (Most Used)
🧠 String Functions Summary
| Operation | Example | Result |
|---|---|---|
| Length | len("Hello") |
5 |
| Membership test | "Py" in "Python" |
True |
| Iterate | for char in "hi": print(char) |
h i |
