Strings, Indexing and Immutability
Quick answer A string is an ordered sequence of characters that you reach by position — forward with 0,1,2… and backward with -1,-2… — and which Python refuses to let you change in place.
A string is a sequence of characters written inside quotes. Python does not care which quotes you use, as long as the opening and closing quote match.
name = 'Aarav Sharma'
city = "Bengaluru"
pin = '''560001'''
print(name)
print(city)
print(pin)
print(type(name))Output:
Aarav Sharma
Bengaluru
560001
Notice pin. It looks like a number, but it is inside quotes, so it is a string. This matters in real life: a PIN code '560001' and an account number '0050100234' must stay strings, because the leading zeros would vanish the moment you made them integers.
Every character has a position. Python gives each character two addresses — one counting from the left starting at 0, and one counting from the right starting at -1.
| Character | P | R | I | O | D | E | M | Y |
|---|---|---|---|---|---|---|---|---|
| Forward index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| Backward index | -8 | -7 | -6 | -5 | -4 | -3 | -2 | -1 |
s = "PRIODEMY"
print(s[0], s[3], s[7])
print(s[-1], s[-8])
print(len(s))Output:
P O Y
Y P
8The last valid forward index is always len(s) - 1, never len(s). Ask for one past the end and Python stops you:
s = "PRIODEMY"
print(s[8])Output:
Traceback (most recent call last):
File "s1c.py", line 2, in
print(s[8])
~^^^
IndexError: string index out of rangeWhy negative indexing exists. Without it you would write s[len(s)-1] every time you wanted the last character. s[-1] says the same thing in three characters and cannot go wrong when the length changes.
Strings are immutable. Once a string object is made, not one character in it can be changed. Try it and Python raises a TypeError:
s = "PRIODEMY"
s[0] = 'X'Output:
Traceback (most recent call last):
File "s1d.py", line 2, in
s[0] = 'X'
~^^^
TypeError: 'str' object does not support item assignmentThe fix is not to edit the string but to build a new one and point the same variable name at it:
s = "PRIODEMY"
print(id(s))
s = "X" + s[1:]
print(s)
print(id(s))Output (the id numbers are memory addresses and will be different every time you run it — only the fact that they differ from each other matters):
2655452667696
XRIODEMY
2655452706352Two different ids prove the point: the old string was not edited, a brand new string was created and s was made to refer to it. Every string method you learn in this chapter works the same way — it hands back a new string and leaves the original untouched.
Escape sequences. Some characters cannot be typed directly, so they are written with a backslash. \n is a newline, \t is a tab, and \\ is one real backslash.
line = "Roll\tName\nA01\tMeera"
print(line)
print(len(line))
path = "C:\\school\\marks.txt"
print(path)
print(len(path))
print(len(""), len(" "), len("Namaste India"))Output:
Roll Name
A01 Meera
19
C:\school\marks.txt
19
0 1 13Read the counts carefully. line is 19 characters even though it prints on two lines, because \n is one character, not two. Likewise \\ in the source is one backslash in the string. And len(" ") is 1 — a space is a character like any other.
Worked example — reading a roll number. A school roll number 11A0342 packs three facts into one string: class, section, serial number. Indexing and slicing pull them apart.
roll = "11A0342"
print("Class code :", roll[0:2])
print("Section :", roll[2])
print("Serial :", roll[-4:])
print("Last digit :", roll[-1])
print("Length :", len(roll))Output:
Class code : 11
Section : A
Serial : 0342
Last digit : 2
Length : 7Using roll[-4:] instead of roll[3:7] is deliberate — it keeps working if the class code becomes three characters long.
- A string is an ordered sequence of characters in matching single, double or triple quotes; the type is str.
- Every character has a forward index (0 to len(s)-1) and a negative index (-1 to -len(s)); going past the end raises IndexError.
- len(s) is a built-in function, not a method, and counts spaces and escape characters too — \n counts as one character.
- Strings are immutable: s[0] = 'X' raises TypeError: 'str' object does not support item assignment. Build a new string with slicing and + instead.
- Because strings are immutable, every string method returns a NEW string; the original variable is unchanged unless you reassign it.
