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.
- 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á".
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.
| Form | Example | When 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 \:
| Escape | Meaning | Example |
|---|---|---|
\n | newline | "line1\nline2" |
\t | tab | "A\tB\tC" |
\\ | literal backslash | "C:\\Users" |
\' | literal single quote | 'it\'s ok' |
\" | literal double quote | "say \"hi\"" |
\0 | null character | rare |
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
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.
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]
- start — first index, included. Default 0.
- stop — one past the last index, excluded. Default
len(s). - step — stride between characters. Default 1. Negative values reverse direction.
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)
16.6 Traversing a String
Traversal means visiting each character of a string one at a time. Two common idioms:
for loop over the characters directly:
s = "Hello" for ch in s: print(ch, end=" ") # H e l l o
for loop with indices (useful when you need the position too):
s = "Hello" for i in range(len(s)): print(i, "→", s[i])
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
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.
16.8 Case-conversion methods
| Method | Effect | Example | Result |
|---|---|---|---|
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
| Method | Returns | Example (on s = "banana") |
|---|---|---|
count(sub) | how many times sub appears | s.count("a") → 3 |
find(sub) | index of first match, or -1 if none | s.find("na") → 2; s.find("z") → -1 |
index(sub) | same as find, but raises ValueError if absent | s.index("na") → 2; s.index("z") → ❌ |
startswith(prefix) | True if s begins with prefix | s.startswith("ba") → True |
endswith(suffix) | True if s ends with suffix | s.endswith("na") → True |
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.
| Method | True 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
| Method | Effect | Example |
|---|---|---|
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' |
strip* variants accept an optional character set: "###hi###".strip("#") → 'hi'. Very useful for trimming characters beyond whitespace.
16.12 Splitting and joining
| Method | Effect | Example | Result |
|---|---|---|---|
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' |
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
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
| Method | What it does | Example | Result |
|---|---|---|---|
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 table | s.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()):
| Function | What it does | Example | Result |
|---|---|---|---|
len(s) | Number of characters | len("Python") | 6 |
str(x) | Convert anything to its string form | str(3.14) | '3.14' |
ord(ch) | Unicode code point of a single character | ord("A") | 65 |
chr(n) | Character with code point n | chr(65) | 'A' |
ascii(x) | Like repr() but escapes non-ASCII | ascii("नमस्ते") | "'\\u0928\\u092e…' |
repr(x) | Debug-friendly string — includes quotes | repr("hi") | "'hi'" |
bin(n) · oct(n) · hex(n) | Integer → binary / octal / hex string | bin(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 float | float("3.14") | 3.14 |
sorted(s) | Sort the characters into a list | sorted("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 point | max("python") | 'y' |
list(s) · tuple(s) | Break the string into a list / tuple of characters | list("abc") | ['a','b','c'] |
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
rgives a raw string — backslashes are literal. - Escape sequences:
\n,\t,\\,\',\". - Basic operations:
+concatenation ·*repetition ·in/not inmembership ·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, stoplen(s), step 1.s[::-1]reverses a string. - Immutable —
s[0] = "x"is an error. Build a new string instead. - Traversal:
for ch in sorfor i in range(len(s))or awhileloop. - Methods always return new strings. Families:
- Case —
upper(),lower(),capitalize(),title(),swapcase(). - Search/Count —
count(),find()(returns -1),index()(raises),startswith(),endswith(). - Classification (→ bool) —
isalpha(),isdigit(),isalnum(),islower(),isupper(),isspace(). - Trim / Replace —
strip(),lstrip(),rstrip(),replace(old, new). - Split / Join —
split(sep)→ list,partition(sep)→ 3-tuple,sep.join(iterable)→ string.
- Case —
- Classic idioms: reverse →
s[::-1]; palindrome →s == s[::-1]; CSV round-trip →",".join(s.split(",")).