VM-LEARNING /class.xi ·track.cs ·ch-2-10 session: 2026_27
$cd ..

~/Strings

root@vm-learning ~ $ open ch-2-10
UNIT 2 ▪ CHAPTER 10
16
Strings
Creation · Indexing · Slicing · Traversal · Methods
A string is an ordered, immutable sequence of Unicode characters enclosed in quotes. Strings are Python's way of representing anything that is textual — a name, an email, a line of a file, an HTML page, even a song's lyrics. Because a string is a sequence, it supports every sequence operation you met in Chapter 9: indexing, slicing, in, +, *, and len(). On top of these, str provides a rich set of methods — around 45 in Python 3 — for cleaning, searching, splitting and re-assembling text.
Three things to remember about strings:
  • They are ordered — every character has a position (index).
  • They are immutable — once created, the characters cannot change. Every "editing" method returns a new string.
  • Python 3 stores strings as Unicode — you can freely put any language's script into a string literal: "नमस्ते", "你好", "Olá".
Learning Outcome 1: Create strings and apply the basic string operations — concatenation, repetition, membership, length.

16.1 Creating a String

Python accepts three kinds of quotes, so you can always pick one that avoids clashing with quotes inside the text.

FormExampleWhen to use
Single quotes'hello'Short strings without apostrophes
Double quotes"O'Brien"When the string itself contains '
Triple quotes"""hello\nworld""" or '''…'''Multi-line strings & docstrings
a = 'Aarav'
b = "O'Brien"                   # single quote inside → use "
c = """This string
spans two lines."""
empty = ""                        # empty string — length 0, perfectly valid

16.1.1 Escape characters

Some characters are hard to type directly — a newline, a tab, a quote inside a quote. Python uses escape sequences starting with \:

EscapeMeaningExample
\nnewline"line1\nline2"
\ttab"A\tB\tC"
\\literal backslash"C:\\Users"
\'literal single quote'it\'s ok'
\"literal double quote"say \"hi\""
\0null characterrare
Prefix a string with r to get a raw string — backslashes become ordinary characters. Very useful for Windows paths and regex patterns:
path = r"C:\Users\Aarav\file.txt"     # no escaping needed

16.2 Basic Operations

Every sequence operation you met in Chapter 9 works on strings.

16.2.1 Concatenation +

first = "Aarav"
last  = "Kumar"
full  = first + " " + last
print(full)               # Aarav Kumar

16.2.2 Repetition *

print("ab" * 3)          # ababab
print("-" * 20)          # --------------------
print("🎉" * 5)          # 🎉🎉🎉🎉🎉

16.2.3 Membership in / not in

s = "Python Programming"
print("Py" in s)          # True
print("java" in s)        # False
print("XYZ" not in s)     # True

16.2.4 Length — len()

print(len("Python"))      # 6
print(len(""))            # 0  — empty string
print(len("a b c"))       # 5  — spaces count
Learning Outcome 2: Use positive and negative indexing and slicing to extract characters and sub-strings.

16.3 Indexing

Each character has two indices — a positive one counted from the left (starting at 0) and a negative one counted from the right (starting at −1). Picking a single character uses square brackets.

Indexing — two ways to reach the same character: P y t h o n 0 1 2 3 4 5 ← positive index −6 −5 −4 −3 −2 −1 ← negative index s = "Python" → s[0] is 'P', s[−1] is 'n', s[2] is 't' or s[−4]
s = "Python"
print(s[0])          # 'P'  — first
print(s[5])          # 'n'  — last
print(s[-1])         # 'n'  — same character, counted from the right
print(s[-3])         # 'h'
# print(s[10])      ❌ IndexError: string index out of range

16.4 Slicing [start:stop:step]

Slicing extracts a sub-string — zero or more consecutive characters. The recipe is identical to range():

s[start : stop : step]
s = "PROGRAMMING"       # indexes 0–10, length 11

print(s[0:4])          # PROG       — chars 0, 1, 2, 3
print(s[4:])           # RAMMING    — from 4 to end
print(s[:3])           # PRO        — start to 3 (exclusive)
print(s[:])             # PROGRAMMING  — whole string (a copy)
print(s[-4:])          # MING       — last 4 characters
print(s[::2])          # PORMIG     — every 2nd character
print(s[::-1])         # GNIMMARGORP  — reversed!
print(s[6:2:-1])       # MARG       — from 6 back to (but not) 2
s[::-1] is the Pythonic idiom for reversing a string. Remember it — palindrome checks use it.

16.5 Strings Are Immutable

You can read any character with indexing, but you cannot write to a character. Python raises TypeError if you try.

s = "Python"
# s[0] = "J"       ❌ TypeError: 'str' object does not support item assignment

# The way to "change" a string is to make a new one:
s = "J" + s[1:]     # "Jython"
print(s)
Learning Outcome 3: Traverse a string using a for loop and a while loop.

16.6 Traversing a String

Traversal means visiting each character of a string one at a time. Two common idioms:

A for loop over the characters directly:
s = "Hello"
for ch in s:
    print(ch, end=" ")        # H e l l o
A for loop with indices (useful when you need the position too):
s = "Hello"
for i in range(len(s)):
    print(i, "→", s[i])
A while loop — traversal from the right:
s = "Hello"
i = len(s) - 1
while i >= 0:
    print(s[i], end=" ")       # o l l e H
    i -= 1
Learning Outcome 4: Apply the built-in string methods covered in the CBSE syllabus.

16.7 String Methods — Overview

Every string object has dozens of built-in methods — functions attached to the object itself. Call them with the dot notation: s.method(arguments). Because strings are immutable, every method that looks like it modifies the string actually returns a new string; the original is untouched.

The CBSE string-method families: String Methods (CBSE Class XI set) Case upper() lower() capitalize() title() swapcase() Search / Count count() find() index() startswith() endswith() Classification isalnum() · isalpha() isdigit() islower() · isupper() isspace() → all return bool Trim / Replace strip() lstrip() · rstrip() replace(old, new) Split / Join split() partition() join() Length len(s) (a built-in FUNCTION, not a method) Every method returns a new string — the original is never modified.

16.8 Case-conversion methods

MethodEffectExampleResult
upper()all letters upper-case"hello".upper()'HELLO'
lower()all letters lower-case"HELLO".lower()'hello'
capitalize()first letter upper, rest lower"hello WORLD".capitalize()'Hello world'
title()first letter of each word upper"hello world".title()'Hello World'
swapcase()swap upper ↔ lower"PyThOn".swapcase()'pYtHoN'

16.9 Search-and-count methods

MethodReturnsExample (on s = "banana")
count(sub)how many times sub appearss.count("a")3
find(sub)index of first match, or -1 if nones.find("na")2;   s.find("z")-1
index(sub)same as find, but raises ValueError if absents.index("na")2;   s.index("z") → ❌
startswith(prefix)True if s begins with prefixs.startswith("ba")True
endswith(suffix)True if s ends with suffixs.endswith("na")True
Prefer find() over index() unless you want the error — the -1 return is easier to handle in an if statement.

16.10 Classification methods — is…()

All classification methods return a Boolean. They check whether the entire string satisfies the property. "" (empty) makes every one of them return False.

MethodTrue when the whole string is…Quick examples (True)
isalpha()letters only"Hello", "नमस्ते"
isdigit()digits only"12345", "007"
isalnum()letters or digits (no spaces, no punctuation)"Hello2026", "abc123"
islower()all cased chars lower-case"hello", "abc 123"
isupper()all cased chars upper-case"HELLO", "ABC 123"
isspace()only whitespace (space, tab, newline)" ", "\t\n"
otp = input("Enter 6-digit OTP: ")
if len(otp) == 6 and otp.isdigit():
    print("OTP accepted")
else:
    print("Invalid — must be exactly 6 digits")

16.11 Trimming and replacing

MethodEffectExample
strip()remove leading and trailing whitespace" hi ".strip()'hi'
lstrip()remove leading (left) whitespace only" hi ".lstrip()'hi '
rstrip()remove trailing (right) whitespace only" hi ".rstrip()' hi'
replace(old, new)replace every occurrence of old with new"ABCABC".replace("A", "X")'XBCXBC'
All three strip* variants accept an optional character set: "###hi###".strip("#")'hi'. Very useful for trimming characters beyond whitespace.

16.12 Splitting and joining

MethodEffectExampleResult
split(sep)break string into a list at every occurrence of sep. Default sep = any whitespace."a,b,c,d".split(",")['a','b','c','d']
partition(sep)split into exactly three parts: before, sep, after — as a tuple."key=value".partition("=")('key','=','value')
sep.join(iterable)concatenate every string in the iterable, inserting sep between them. The inverse of split."-".join(["a","b","c"])'a-b-c'
Split & join — the round-trip:
line = "Aarav,Kavya,Ishan,Priya"
names = line.split(",")               # ['Aarav','Kavya','Ishan','Priya']
print(names)

csv_back = ",".join(names)             # 'Aarav,Kavya,Ishan,Priya'
print(csv_back)

# Split on whitespace when no argument is given:
sentence = "Python is fun"
words = sentence.split()                 # ['Python','is','fun']
print(len(words))                       # 3
Important quirk: split() is a method on the string being cut; join() is a method on the separator. Beginners often swap them and get confused.
",".join(["a", "b"])       # ✓ correct — separator calls join
["a", "b"].join(",")          # ❌ AttributeError — list has no join

16.13 Beyond the Syllabus — Other Useful str Methods

Python's str class has around 45 methods. The 23 covered so far are those named in the CBSE Class XI syllabus. You may meet the following extras in real-world code — they are not required for the exam, but worth knowing.

16.13.1 More string methods

MethodWhat it doesExampleResult
center(width, fill)Pad on both sides to width"hi".center(10, "-")'----hi----'
ljust(width, fill)Left-justify, pad on right"hi".ljust(6, "*")'hi****'
rjust(width, fill)Right-justify, pad on left"7".rjust(3, "0")'007'
zfill(width)Zero-pad on the left to width"42".zfill(5)'00042'
rfind(sub) / rindex(sub)Like find/index but search from the right"banana".rfind("a")5
rsplit(sep, n)Split starting from the right; n caps the splits"a.b.c".rsplit(".", 1)['a.b', 'c']
rpartition(sep)Like partition but from the right"a=b=c".rpartition("=")('a=b', '=', 'c')
splitlines()Split on line-breaks — no trailing blanks"a\nb\nc".splitlines()['a', 'b', 'c']
expandtabs(n)Replace each \t with spaces"a\tb".expandtabs(4)'a b'
casefold()Aggressive lower-case — safe for non-English text"ß".casefold()'ss'
format(...)Older formatting API (f-strings replace it)"Hi {}".format("A")'Hi A'
encode(enc)Convert to bytes in a given encoding"hi".encode("utf-8")b'hi'
maketrans() & translate()Character-by-character translation tables.translate(str.maketrans("ab", "xy"))every 'a'→'x', 'b'→'y'
istitle()All words start with upper-case"Hello World".istitle()True
isdecimal() / isnumeric()Stricter digit checks (include Roman / Devanagari numerals)"१२३".isnumeric()True
isprintable()Every char is printable"hi\n".isprintable()False
isascii()All chars are ASCII (< 128)"Aarav".isascii()True
isidentifier()Is the string a valid Python identifier?"name_1".isidentifier()True
removeprefix(p) / removesuffix(s)Python 3.9+ — strip a fixed prefix / suffix"unhappy".removeprefix("un")'happy'

16.13.2 Built-in FUNCTIONS that work with strings

These are functions (called as f(x)), not methods (called as x.f()):

FunctionWhat it doesExampleResult
len(s)Number of characterslen("Python")6
str(x)Convert anything to its string formstr(3.14)'3.14'
ord(ch)Unicode code point of a single characterord("A")65
chr(n)Character with code point nchr(65)'A'
ascii(x)Like repr() but escapes non-ASCIIascii("नमस्ते")"'\\u0928\\u092e…'
repr(x)Debug-friendly string — includes quotesrepr("hi")"'hi'"
bin(n) · oct(n) · hex(n)Integer → binary / octal / hex stringbin(10), hex(255)'0b1010', '0xff'
int(s, base)Parse a string into an int (base 2–36)int("1010", 2)10
float(s)Parse a string into a floatfloat("3.14")3.14
sorted(s)Sort the characters into a listsorted("dcba")['a','b','c','d']
reversed(s)Iterator over characters in reverse"".join(reversed("abc"))'cba'
max(s) · min(s)Largest / smallest character by Unicode code pointmax("python")'y'
list(s) · tuple(s)Break the string into a list / tuple of characterslist("abc")['a','b','c']
Quick way to explore. In an interactive shell, type dir(str) to see every method, or help(str.method_name) to read its documentation — e.g., help(str.split).

16.14 Worked Programs

16.14.1 Count vowels in a string

s = input("Enter a string: ").lower()
vowels = "aeiou"
count = 0
for ch in s:
    if ch in vowels:
        count += 1
print("Vowels found:", count)
Sample: "Python Programming" → 4 vowels (o, o, a, i).

16.14.2 Palindrome check

A palindrome reads the same forwards and backwards: MADAM, nitin, racecar, 12321.

s = input("Enter a word: ").lower()
if s == s[::-1]:              # reverse using slicing
    print(s, "is a palindrome")
else:
    print(s, "is not a palindrome")

16.14.3 Count upper-case, lower-case, digits, spaces

s = input("Enter a string: ")
u = l = d = sp = 0
for ch in s:
    if   ch.isupper():  u  += 1
    elif ch.islower():  l  += 1
    elif ch.isdigit():  d  += 1
    elif ch.isspace():  sp += 1
print(f"Upper={u}  Lower={l}  Digits={d}  Spaces={sp}")
For input "Hello World 2026": Upper=2 Lower=8 Digits=4 Spaces=2

16.14.4 Convert case (every letter)

s = input("Enter a string: ")
print("UPPER:",     s.upper())
print("lower:",     s.lower())
print("Capitalized:", s.capitalize())
print("Title:",     s.title())
print("Swapped:",   s.swapcase())

📌 Quick Revision — Chapter 16 at a Glance

  • String = ordered, immutable sequence of Unicode characters. Created with '…', "…", or """…""" (multi-line).
  • Prefix r gives a raw string — backslashes are literal.
  • Escape sequences: \n, \t, \\, \', \".
  • Basic operations: + concatenation · * repetition · in/not in membership · len(s) length.
  • Indexing: s[0] first · s[-1] last. Out-of-range → IndexError.
  • Slicing s[start:stop:step] — stop is excluded. Defaults: start 0, stop len(s), step 1. s[::-1] reverses a string.
  • Immutables[0] = "x" is an error. Build a new string instead.
  • Traversal: for ch in s or for i in range(len(s)) or a while loop.
  • Methods always return new strings. Families:
    • Caseupper(), lower(), capitalize(), title(), swapcase().
    • Search/Countcount(), find() (returns -1), index() (raises), startswith(), endswith().
    • Classification (→ bool)isalpha(), isdigit(), isalnum(), islower(), isupper(), isspace().
    • Trim / Replacestrip(), lstrip(), rstrip(), replace(old, new).
    • Split / Joinsplit(sep) → list, partition(sep) → 3-tuple, sep.join(iterable) → string.
  • Classic idioms: reverse → s[::-1]; palindrome → s == s[::-1]; CSV round-trip → ",".join(s.split(",")).
🧠Practice Quiz — test yourself on this chapter