CBSE Class 11 Computer Science Chapter 8 — Strings
Strings are one of the most commonly used data types in Python. Whether you are working with names, messages, or file data, understanding how to create, manipulate, and format strings is essential. This chapter covers everything from basic string creation to advanced slicing, methods, and formatting — all aligned with the NCERT syllabus for CBSE Class 11.
Chapter Introduction
A string is a sequence of characters enclosed in quotes. In Python, strings are immutable — once created, they cannot be changed. Every operation that seems to modify a string actually creates a new one. This property makes strings safe and efficient but also means you need to understand how slicing, methods, and formatting work to use them effectively.
Strings are everywhere in real-world programming: processing user input, displaying messages, reading files, and handling web data. Mastering strings is a fundamental skill for any Python programmer and a high-scoring topic in CBSE exams.
Key Definitions
| Term | Definition |
|---|---|
| String | A sequence of characters enclosed in single, double, or triple quotes |
| Immutability | The property that a string cannot be changed after creation |
| Indexing | Accessing individual characters by their position (index) |
| Slicing | Extracting a portion of a string using a range of indices |
| String method | A built-in function that operates on a string object |
| Concatenation | Joining two or more strings using the + operator |
| Repetition | Repeating a string multiple times using the * operator |
| Escape sequence | A special character combination starting with \ (e.g., \n, \t) |
| Raw string | A string prefixed with r that treats backslashes as literal characters |
| f-string | A formatted string literal prefixed with f that allows embedded expressions |
| Palindrome | A string that reads the same forwards and backwards (e.g., "madam") |
Detailed Concepts
1. Creating Strings
Python offers several ways to create strings.
Single quotes:
name = 'KalviGavani'
Double quotes:
name = "KalviGavani"
Triple quotes (for multi-line strings):
message = """This is a
multi-line string
in Python."""
Empty string:
empty = ''
empty2 = ""
Escape sequences:
Escape sequences let you include special characters in strings.
| Escape Sequence | Meaning |
|---|---|
\\n | Newline |
\\t | Tab |
\\\\ | Backslash |
\\' | Single quote |
\\" | Double quote |
\\r | Carriage return |
print("Hello\tWorld") # Output: Hello World (tab space)
print("Line1\nLine2") # Output: Line1
# Line2
print("She said, \"Hi\"") # Output: She said, "Hi"
Raw strings:
Prefix with r to treat backslashes as literal characters. Useful for file paths and regular expressions.
path = r"C:\new\folder"
print(path) # Output: C:\new\folder (no escape processing)
2. String Immutability
Strings in Python are immutable — they cannot be changed after creation. Any operation that appears to modify a string actually creates a new string object.
s = "Hello"
# s[0] = "J" # ERROR — 'str' object does not support item assignment
When you "change" a string, Python creates a new one:
s = "Hello"
print(id(s)) # some memory address, e.g., 140234567890
s = s + " World"
print(id(s)) # different memory address — a NEW string was created
Similarly, methods like upper() and replace() return new strings; they do not modify the original:
s = "hello"
upper_s = s.upper()
print(s) # Output: hello (original unchanged)
print(upper_s) # Output: HELLO (new string returned)
3. Accessing Characters
Each character in a string has a position called an index. Python supports two types of indexing.
3.1 Positive Indexing
Starts from 0 at the left and goes up to len(string) - 1.
s = "PYTHON"
# P Y T H O N
# 0 1 2 3 4 5
print(s[0]) # Output: P
print(s[3]) # Output: H
print(s[5]) # Output: N
3.2 Negative Indexing
Starts from -1 at the right and goes backwards.
s = "PYTHON"
# P Y T H O N
# -6 -5 -4 -3 -2 -1
print(s[-1]) # Output: N
print(s[-3]) # Output: H
print(s[-6]) # Output: P
Accessing an index out of range causes an IndexError:
s = "PYTHON"
# print(s[6]) # IndexError: string index out of range
4. String Slicing
Slicing extracts a portion of a string. The syntax is:
s[start:stop:step]
start— index where the slice begins (default: 0)stop— index where the slice ends (exclusive; default: end of string)step— increment between indices (default: 1)
Basic slicing:
s = "PYTHON"
print(s[1:4]) # Output: YTH (indices 1, 2, 3)
print(s[0:3]) # Output: PYT
print(s[2:5]) # Output: THO
Omitting start or stop:
s = "PYTHON"
print(s[:4]) # Output: PYTH (from beginning to index 3)
print(s[2:]) # Output: THON (from index 2 to end)
print(s[:]) # Output: PYTHON (entire string — a copy)
Negative indices in slicing:
s = "PYTHON"
print(s[-4:-1]) # Output: THO
print(s[:-2]) # Output: PYTH
print(s[-3:]) # Output: HON
Step value:
s = "PYTHON"
print(s[::2]) # Output: PTO (every 2nd character)
print(s[1::2]) # Output: YHN (starting at 1, every 2nd)
print(s[::3]) # Output: PH (every 3rd character)
Negative step (reverse direction):
s = "PYTHON"
print(s[::-1]) # Output: NOHTYP (reverse the string)
print(s[::-2]) # Output: NTP (reverse, every 2nd)
print(s[4:1:-1]) # Output: OHT (from index 4 down to 2)
5. String Operations
5.1 Concatenation (+)
Joining two strings together.
first = "Kalvi"
last = "Gavani"
full = first + last
print(full) # Output: KalviGavani
greeting = "Hello, " + "World!"
print(greeting) # Output: Hello, World!
You cannot concatenate a string with a number directly:
# print("Age: " + 16) # TypeError
print("Age: " + str(16)) # Output: Age: 16
5.2 Repetition (*)
Repeating a string multiple times.
pattern = "Ha" * 3
print(pattern) # Output: HaHaHa
line = "-" * 30
print(line) # Output: ------------------------------
5.3 Membership (in / not in)
Check whether a substring exists in a string.
s = "KalviGavani"
print("Kalvi" in s) # Output: True
print("gavani" in s) # Output: False (case-sensitive)
print("Hello" not in s) # Output: True
6. String Methods
Python provides many built-in string methods. These return new strings (since strings are immutable).
6.1 Case Conversion Methods
| Method | Description | Example |
|---|---|---|
upper() | Converts to uppercase | "hello".upper() → "HELLO" |
lower() | Converts to lowercase | "HELLO".lower() → "hello" |
title() | First letter of each word uppercase | "hello world".title() → "Hello World" |
capitalize() | First character uppercase, rest lowercase | "hELLO".capitalize() → "Hello" |
swapcase() | Swaps upper and lower case | "HeLLo".swapcase() → "hEllO" |
s = "hello WORLD"
print(s.upper()) # Output: HELLO WORLD
print(s.lower()) # Output: hello world
print(s.title()) # Output: Hello World
print(s.capitalize()) # Output: Hello world
print(s.swapcase()) # Output: HELLO world
6.2 Search Methods
| Method | Description | Example |
|---|---|---|
find(sub) | Returns lowest index of sub; -1 if not found | "hello".find("ll") → 2 |
rfind(sub) | Returns highest index of sub; -1 if not found | "hello".rfind("l") → 3 |
index(sub) | Like find, but raises ValueError if not found | "hello".index("ll") → 2 |
rindex(sub) | Like rfind, but raises ValueError if not found | "hello".rindex("l") → 3 |
count(sub) | Counts non-overlapping occurrences | "banana".count("an") → 2 |
startswith(sub) | True if string starts with sub | "hello".startswith("he") → True |
endswith(sub) | True if string ends with sub | "hello".endswith("lo") → True |
s = "KalviGavani"
print(s.find("Gav")) # Output: 5
print(s.find("XYZ")) # Output: -1
print(s.count("a")) # Output: 2
print(s.startswith("Kalvi")) # Output: True
print(s.endswith("ani")) # Output: True
6.3 Modification Methods
| Method | Description | Example |
|---|---|---|
replace(old, new) | Replaces all occurrences | "hello".replace("l", "r") → "herro" |
split(sep) | Splits into list by separator | "a,b,c".split(",") → ["a","b","c"] |
join(iterable) | Joins iterable with string as separator | "-".join(["a","b","c"]) → "a-b-c" |
strip() | Removes leading and trailing whitespace | " hi ".strip() → "hi" |
lstrip() | Removes leading whitespace | " hi ".lstrip() → "hi " |
rstrip() | Removes trailing whitespace | " hi ".rstrip() → " hi" |
# replace
s = "I love Python"
print(s.replace("Python", "Java")) # Output: I love Java
# split
csv = "red,green,blue"
colors = csv.split(",")
print(colors) # Output: ['red', 'green', 'blue']
# join
words = ["Hello", "World"]
print(" ".join(words)) # Output: Hello World
# strip
s = " Hello "
print(s.strip()) # Output: Hello
print(s.lstrip()) # Output: Hello (trailing spaces remain)
6.4 Check Methods
| Method | Description | Example |
|---|---|---|
isalpha() | True if all characters are alphabetic | "hello".isalpha() → True |
isdigit() | True if all characters are digits | "123".isdigit() → True |
isalnum() | True if all characters are alphanumeric | "abc123".isalnum() → True |
isspace() | True if all characters are whitespace | " ".isspace() → True |
isupper() | True if all cased characters are uppercase | "HELLO".isupper() → True |
islower() | True if all cased characters are lowercase | "hello".islower() → True |
print("ABC".isalpha()) # Output: True
print("123".isdigit()) # Output: True
print("abc123".isalnum()) # Output: True
print(" ".isspace()) # Output: True
6.5 Alignment Methods
| Method | Description | Example |
|---|---|---|
center(width) | Centers string within width | "hi".center(10) → " hi " |
ljust(width) | Left-aligns within width | "hi".ljust(10) → "hi " |
rjust(width) | Right-aligns within width | "hi".rjust(10) → " hi" |
name = "Python"
print(name.center(20)) # Output: Python
print(name.ljust(20, '-')) # Output: Python--------------
print(name.rjust(20, '-')) # Output: --------------Python
6.6 The len() Function
len() is a built-in function (not a string method) that returns the number of characters in a string.
print(len("Hello")) # Output: 5
print(len("KalviGavani")) # Output: 11
print(len("")) # Output: 0
6.7 The format() Method
The format() method inserts values into a string using placeholders.
name = "Arun"
age = 17
print("My name is {} and I am {} years old.".format(name, age))
# Output: My name is Arun and I am 17 years old.
# With positional indices
print("{0} scored {1} marks in {2}.".format("Priya", 95, "Maths"))
# Output: Priya scored 95 marks in Maths.
# With named placeholders
print("{name} lives in {city}.".format(name="Kavya", city="Chennai"))
# Output: Kavya lives in Chennai.
7. String Formatting
Python offers three ways to format strings with variables.
7.1 Old-style (% operator)
name = "Ravi"
age = 16
print("Name: %s, Age: %d" % (name, age))
# Output: Name: Ravi, Age: 16
pi = 3.14159
print("Pi = %.2f" % pi) # Output: Pi = 3.14
| Format Specifier | Meaning |
|---|---|
%s | String |
%d | Integer |
%f | Float |
%.2f | Float with 2 decimal places |
7.2 .format() method
name = "Sita"
marks = 98
print("{} scored {} marks.".format(name, marks))
# Output: Sita scored 98 marks.
print("{1} scored {0} marks.".format(marks, name))
# Output: Sita scored 98 marks.
7.3 f-strings (Python 3.6+)
The most readable and modern approach. Prefix the string with f and embed expressions in {}.
name = "Ananya"
age = 17
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Ananya and I am 17 years old.
# Expressions inside f-strings
a = 5
b = 3
print(f"{a} + {b} = {a + b}") # Output: 5 + 3 = 8
# Formatting numbers
pi = 3.14159
print(f"Pi = {pi:.2f}") # Output: Pi = 3.14
# Method calls in f-strings
print(f"Hello, {name.upper()}!") # Output: Hello, ANANYA!
8. Traversing a String
8.1 Using a for loop
The simplest way to visit each character.
s = "Python"
for char in s:
print(char)
# Output:
# P
# y
# t
# h
# o
# n
8.2 Using a for loop with range() and indexing
Useful when you need the index.
s = "Python"
for i in range(len(s)):
print(f"Index {i}: {s[i]}")
# Output:
# Index 0: P
# Index 1: y
# Index 2: t
# Index 3: h
# Index 4: o
# Index 5: n
8.3 Using a while loop
s = "Python"
i = 0
while i < len(s):
print(s[i])
i += 1
9. Common String Programs
9.1 Palindrome Check
def is_palindrome(s):
"""Check if a string is a palindrome."""
s = s.lower() # make case-insensitive
return s == s[::-1]
print(is_palindrome("madam")) # Output: True
print(is_palindrome("hello")) # Output: False
print(is_palindrome("RaceCar")) # Output: True
9.2 Count Vowels and Consonants
def count_vowels_consonants(s):
"""Count vowels and consonants in a string."""
vowels = "aeiouAEIOU"
v = c = 0
for char in s:
if char.isalpha():
if char in vowels:
v += 1
else:
c += 1
return v, c
v, c = count_vowels_consonants("Hello World")
print(f"Vowels: {v}, Consonants: {c}")
# Output: Vowels: 3, Consonants: 7
9.3 Reverse a String
def reverse_string(s):
"""Reverse a string using slicing."""
return s[::-1]
print(reverse_string("Python")) # Output: nohtyP
9.4 Anagram Check
def is_anagram(s1, s2):
"""Check if two strings are anagrams of each other."""
return sorted(s1.lower()) == sorted(s2.lower())
print(is_anagram("listen", "silent")) # Output: True
print(is_anagram("hello", "world")) # Output: False
9.5 Count Occurrences of a Substring
def count_substring(main_str, sub):
"""Count how many times sub appears in main_str."""
return main_str.count(sub)
print(count_substring("banana", "an")) # Output: 2
9.6 Replace Characters
def replace_vowels(s):
"""Replace all vowels with '*'."""
vowels = "aeiouAEIOU"
result = ""
for char in s:
if char in vowels:
result += "*"
else:
result += char
return result
print(replace_vowels("Hello World")) # Output: H*ll* W*rld
Common Mistakes
1. Trying to modify a string by index — s[0] = "X" raises a TypeError. Strings are immutable.
2. Confusing find() and index() — find() returns -1 when the substring is not found; index() raises a ValueError.
3. Using == for case-insensitive comparison without converting — "Hello" == "hello" is False. Use .lower() or .upper() first.
4. Off-by-one errors in slicing — Remember that the stop index is exclusive. s[0:3] gives characters at indices 0, 1, 2 — not 3.
5. Forgetting that string methods return new strings — Calling s.upper() without assigning the result does not change s.
6. Using + to concatenate with non-strings — "Age: " + 16 causes a TypeError. Convert with str(16) or use f-strings.
7. Not handling empty strings — Methods like isalpha() and isdigit() return False for empty strings.
8. Confusing split() without arguments — s.split() splits on any whitespace and removes empty strings; s.split(" ") splits only on spaces and can produce empty strings.
Exam Tips
1. For output questions, trace indexing carefully. Write the index positions above the string: H e l l o with 0 1 2 3 4 beneath.
2. Remember slicing rules: s[start:stop] includes start but excludes stop. This is tested very frequently.
3. Know the difference between find() and index(): find() returns -1 for not found; index() raises ValueError. Examiners love asking this.
4. f-strings are the preferred formatting method but you should also know % formatting and .format() since NCERT and older exam papers may use them.
5. For palindrome programs, always mention case handling — convert to lowercase before comparing.
6. When writing string programs, handle edge cases: empty string, single character, all same characters.
7. Memorise the most common methods: upper(), lower(), find(), replace(), split(), join(), strip(), count(), startswith(), endswith().
8. For "what is the output" questions with methods, remember that methods do not modify the original string. The original remains unchanged.
9. Negative indexing is frequently tested. Remember: the last character is at index -1, the second last at -2, and so on.
10. Practise slicing with all three parts — start, stop, and step — especially negative step for reversal.
Quick Revision Notes
- Strings are immutable sequences of characters.
- Created with single quotes
'...', double quotes"...", or triple quotes"""...""". - Positive indexing starts at 0; negative indexing starts at -1 from the right.
- Slicing:
s[start:stop:step]— start is inclusive, stop is exclusive. s[::-1]reverses a string.- Concatenation with
+; repetition with*; membership within/not in. - String methods return new strings — they do not modify the original.
find()returns-1if not found;index()raisesValueError.split()converts a string to a list;join()converts a list to a string.strip()removes leading/trailing whitespace;lstrip()andrstrip()for one side.isalpha(),isdigit(),isalnum()check character types.- Three formatting styles:
%operator,.format(), and f-strings (preferred). - f-strings:
f"{variable}"— embed expressions inside curly braces. - Traverse strings with
for char in s:orfor i in range(len(s)):. - Common programs: palindrome, count vowels, reverse, anagram check.
For complete exercise solutions, see [Strings — NCERT Class 11 Computer Science](/class/11/computer-science/solutions/cbse-strings-exercise-solutions).
