Python Strings — Indexing, Slicing, F-Strings & Methods
🐍 Python 3
🟢 Lesson 8 of 12
📂 Phase 1: Python Basics
📅 2026 Edition
Master string immutability, zero-based positive & negative indexing, slice syntax [start:stop:step], modern f-strings formatting, and essential string methods.
1String Creation & Immutability
Strings in Python are ordered sequences of Unicode characters enclosed in single quotes '...', double quotes "...", or triple quotes """...""".
Crucial Rule: Strings are immutable. Once created, you cannot change individual characters in-place (e.g. s[0] = 'X' raises TypeError). You must create a new string object instead.
2Zero-Based Positive and Negative Indexing
String: P Y T H O N
Positive: 0 1 2 3 4 5
Negative:-6 -5 -4 -3 -2 -1
3String Slicing Syntax: [start : stop : step]
s[0:3] -> Characters from index 0 up to (but not including) index 3.
s[2:] -> From index 2 to the end of string.
s[:4] -> From start up to index 4.
s[::-1] -> Step is -1: reverses the entire string!
4Modern Formatted String Literals (F-Strings)
Introduced in Python 3.6, f-strings provide the cleanest way to interpolate variables and expressions directly inside strings:
name = "Balaji"
score = 98.456
print(f"Student: {name}, Score: {score:.2f}%")
💻 Complete Executable Code Example
text = "Python Programming in 2026"
# Indexing and Slicing
print("Original Text:", text)
print("First Char [0]:", text[0])
print("Last Char [-1]:", text[-1])
print("Slice [0:6]:", text[0:6])
print("Reversed [::-1]:", text[::-1])
# Essential String Methods
sample = " hello, world! python is awesome. "
print("
Cleaned & Formatted:")
print("strip():", sample.strip())
print("upper():", sample.strip().upper())
print("title():", sample.strip().title())
print("replace():", sample.strip().replace("world", "developers"))
# Splitting and Joining
words = text.split(" ")
print("
Split into words list:", words)
print("Joined with hyphens:", "-".join(words))
⚠️ Common Pitfall: Trying to Mutate a String In-Place
Writing s[0] = "H" raises TypeError: "str" object does not support item assignment. Instead, use slicing: s = "H" + s[1:]
💻 Try It Yourself — Hands-on Practice Challenge
Check whether a word or phrase reads identically backwards and forwards.
def check_palindrome(word: str) -> bool:
cleaned = word.lower().replace(" ", "")
return cleaned == cleaned[::-1]
test_words = ["racecar", "Python", "madam", "Never odd or even"]
for w in test_words:
result = "✅ Palindrome" if check_palindrome(w) else "❌ Not palindrome"
print(f"'{w}' -> {result}")
Run This Code in Our Online Compiler →
❓ Frequently Asked Questions (FAQ)
Q: Why are f-strings faster than .format() or % formatting?
F-strings are evaluated at runtime directly as optimized bytecode expressions rather than parsing format specification strings.
OC
Written by Our Compiler Technical Editorial Team
Reviewed for accuracy & tested on Python 3.12+ runtime · Last updated August 2026