Loading notes...
Loading notes...
Class 11 • Chapter 7
Chapter 7 explores String Manipulation, emphasizing string immutability, index-based access, slicing techniques, and powerful built-in string methods.
In Python, a String is a sequence of characters enclosed in quotes. Strings are one of the most frequently used data types because almost all human-readable data (names, addresses, passwords) is processed as text. Python provides incredibly powerful, built-in tools to slice, search, and modify strings with minimal effort.
7.1 String Creation and Immutability
You can create strings using single quotes (`'...'`), double quotes (`"..."`), or triple quotes (`'''...'''` or `"""..."""`). Triple quotes are unique because they allow strings to span multiple lines. CRITICAL RULE: Strings in Python are Immutable. Once a string is created in memory, it cannot be changed. If you try to modify a string, Python destroys the old one and creates a brand new string in memory.
name = "Basant"
# name[0] = "P" <-- THIS WILL CRASH! Strings are immutable.
# To 'modify', we must create a new string
name = "P" + name[1:] # This is valid
paragraph = """
This is a
multi-line
string.
"""7.2 String Indexing
Every character in a string is assigned an integer index indicating its position. Python supports both Forward Indexing (starting at 0) and Backward Indexing (starting at -1 from the very end).
text = "PYTHON"
# Forward: P=0, Y=1, T=2, H=3, O=4, N=5
# Backward: P=-6, Y=-5, T=-4, H=-3, O=-2, N=-1
print(text[0]) # Output: P
print(text[-1]) # Output: N (The fastest way to get the last character)7.3 String Slicing
Slicing allows you to extract a specific substring from a larger string. The syntax is `string[start : stop : step]`.
word = "PROGRAMMING"
print(word[0:7]) # 'PROGRAM' (Extracts indices 0 to 6)
print(word[3:]) # 'GRAMMING' (From index 3 to the end)
print(word[:3]) # 'PRO' (From beginning to index 2)
print(word[::2]) # 'PORMIG' (Every 2nd character)
print(word[::-1]) # 'GNIMMARGORP' (The easiest way to reverse a string!)7.4 String Operators
Python overloads mathematical operators to work with strings.
7.5 Built-in String Methods
Methods are functions that belong to the string object. Because strings are immutable, methods NEVER modify the original string; they always return a brand new string.