CHAPTER PDF
Complete curriculum textbook chapter document for reading and offline study.
NOTES
Complete conceptual breakdown, formulas, diagrams, and memory aids.
Chapter 8: Strings
Complete notes based on the uploaded NCERT Reprint 2026–27 chapter, with definitions, syntax, worked examples, program explanations, method reference tables and exercises.
Chapter overview
A string is Python's sequence data type for text. This chapter covers creating strings, accessing characters, immutability, operators, slicing, traversal, built-in functions, string methods and user-defined functions for common text-processing tasks.
Source: uploaded NCERT Class XI Computer Science, Chapter 8 “Strings”, Reprint 2026–27, printed pages 175–188 (14 PDF pages). The indexing table and string-method reference tables have been incorporated in explanatory form.
8.1 Introduction
A sequence is an orderly collection of items, where each item is identified by an integer index. Chapter 5 introduced strings, lists and tuples as sequence data types. A dictionary, also introduced in Chapter 5, belongs to the mapping category. This chapter studies strings in detail; lists are covered in Chapter 9, while tuples and dictionaries are discussed in Chapter 10.
8.2 Strings
A string is a sequence made up of one or more Unicode characters. A character may be a letter, digit, whitespace or any other symbol. Python does not have a separate character data type; a string of length one is treated as a character.
Creating strings
A string can be enclosed in single quotes, double quotes or triple quotes.
str1 = 'Hello World!'
str2 = "Hello World!"
str3 = """Hello World!"""
str4 = '''Hello World!'''All four variables contain the same text. Triple-quoted strings can extend over multiple lines:
message = """Hello World!
Welcome to the world of Python"""'A' is still a string, not a separate char type.8.2.1 Accessing Characters in a String (Indexing)
Indexing accesses an individual character using its position, written in square brackets [].
- First character from the left: index
0. - For a string of length
n, last positive index:n-1. - Negative indexing begins at the right: rightmost character is
-1, leftmost is-n. - An index must be an integer (positive, zero or negative).
- An out-of-range index raises
IndexError; a non-integer index raisesTypeError.
Index table: “Hello World!”
The string has 12 characters, including the space. This table corresponds to Table 8.1 on printed page 177.
| Character | H | e | l | l | o | space | W | o | r | l | d | ! |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Positive index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
| Negative index | -12 | -11 | -10 | -9 | -8 | -7 | -6 | -5 | -4 | -3 | -2 | -1 |
Examples
str1 = 'Hello World!'
print(str1[0]) # H
print(str1[6]) # W
print(str1[11]) # !
print(str1[-1]) # !
print(str1[-12]) # H
print(str1[2 + 4]) # W; expression evaluates to index 6str1[15] raises IndexError: string index out of range. str1[1.5] raises TypeError because an index must be an integer.
Using len()
The built-in len() function returns the number of characters, including spaces and punctuation.
str1 = 'Hello World!'
n = len(str1)
print(n) # 12
print(str1[n - 1]) # !
print(str1[-n]) # Hs[len(s)-1] or simply s[-1].8.2.2 String is Immutable
A string is an immutable data type. Its contents cannot be changed after it has been created.
str1 = "Hello World!"
str1[1] = 'a'This raises TypeError: 'str' object does not support item assignment.
Creating a modified copy
Build a new string instead of changing a character in place:
str1 = "Hello World!"
str2 = str1[0] + 'a' + str1[2:]
print(str1) # Hello World!
print(str2) # Hallo World!The original remains unchanged; the modified text is stored in a new string.
8.3 String Operations
Python supports several operations on strings because a string is a sequence of characters. The chapter covers concatenation, repetition, membership and slicing.
8.3.1 Concatenation
Concatenation means joining strings. The plus operator + returns a new string containing both strings joined together.
new_string = string1 + string2
str1 = 'Hello'
str2 = 'World!'
str3 = str1 + str2
print(str3) # HelloWorld!
print(str1) # Hello
print(str2) # World!No space is inserted automatically. To include one, use str1 + ' ' + str2. The original strings remain unchanged.
8.3.2 Repetition
The repetition operator * repeats a string a specified number of times.
str1 = 'Hello'
print(str1 * 2) # HelloHello
print(str1 * 5) # HelloHelloHelloHelloHello
print(str1) # HelloA zero or negative repetition count produces an empty string. The original string is not modified.
8.3.3 Membership
The operators in and not in check whether one string occurs as a substring of another.
inTrue if the left operand occurs in the right operand; otherwise False.
not inTrue if the left operand does not occur in the right operand; otherwise False.
str1 = 'Hello World!'
print('W' in str1) # True
print('Wor' in str1) # True
print('My' in str1) # False
print('My' not in str1) # True
print('Hello' not in str1) # FalseMembership is case-sensitive: 'hello' in 'Hello' returns False.
8.3.4 Slicing
Slicing retrieves part of a string (a substring) by specifying an index range.
Syntax
string[start : stop]
string[start : stop : step]- Start index is included.
- Stop index is excluded.
- Default step is 1.
- If start is omitted, slicing begins at the beginning.
- If stop is omitted, slicing continues to the end.
str1 = 'Hello World!'
print(str1[1:5]) # ello
print(str1[7:10]) # orl
print(str1[3:20]) # lo World! (stop clipped to end)
print(str1[7:2]) # '' (empty string)
print(str1[:5]) # Hello
print(str1[6:]) # World!
print(str1[:]) # Hello World!Step size
In s[start:stop:step], Python selects every step-th character while moving towards the stop boundary.
str1 = 'Hello World!'
print(str1[0:10:2]) # HloWr
print(str1[0:10:3]) # HlWlNegative-index slicing
str1 = 'Hello World!'
print(str1[-6:-1]) # WorldThis selects indices -6, -5, -4, -3 and -2; -1 is excluded.
Reverse a string with slicing
str1 = 'Hello World!'
print(str1[::-1]) # !dlroW olleH8.4 Traversing a String
Traversing means accessing every character one by one. The chapter demonstrates two techniques.
(A) Using a for loop
str1 = 'Hello World!'
for ch in str1:
print(ch, end='')Output: Hello World!. The loop starts at the first character and ends automatically after the last character. No index variable is needed.
(B) Using a while loop
str1 = 'Hello World!'
index = 0
while index < len(str1):
print(str1[index], end='')
index += 1Output: Hello World!. The index ranges from 0 to len(str1)-1. It must be incremented so the condition eventually becomes false.
| for loop | while loop |
|---|---|
| Iterates directly over characters. | Uses an index to access characters. |
| Simple when every character must be processed. | Useful when index-based control is required. |
| Ends automatically after the final character. | Ends when the condition becomes false. |
8.5 String Methods and Built-in Functions
Python provides built-in functions and string methods for text manipulation. Methods use dot notation:
string_variable.method_name(arguments)Because strings are immutable, methods that appear to change a string actually return a new string.
Length and case conversion
| Method/function | Description | Example → result |
|---|---|---|
len(s) | Returns string length. | len('Hello World!') → 12 |
s.title() | First letter of every word uppercase, remaining letters lowercase. | 'hello WORLD!'.title() → 'Hello World!' |
s.lower() | Converts uppercase letters to lowercase. | 'hello WORLD!'.lower() → 'hello world!' |
s.upper() | Converts lowercase letters to uppercase. | 'hello WORLD!'.upper() → 'HELLO WORLD!' |
Searching and counting
| Method | Description | Example |
|---|---|---|
s.count(sub[,start[,end]]) | Counts occurrences; optional range limits search. | 'Hello World! Hello Hello'.count('Hello') → 3 |
s.find(sub[,start[,end]]) | Returns first matching index; -1 if absent. | 'Hello'.find('He') → 0; 'Hello'.find('xy') → -1 |
s.index(sub[,start[,end]]) | Like find(), but raises ValueError if absent. | 'Hello'.index('e') → 1 |
s.endswith(x) | True if string ends with x. | 'Hello!'.endswith('!') → True |
s.startswith(x) | True if string starts with x. | 'Hello!'.startswith('He') → True |
Character-testing methods
| Method | Returns True when... | Examples |
|---|---|---|
isalnum() | String is non-empty and all characters are letters or digits. Spaces and symbols make it False. | 'HelloWorld2'.isalnum() → True; 'Hello World'.isalnum() → False |
islower() | At least one lowercase letter exists and no uppercase letter exists. Non-letters are allowed. | 'hello 1234'.islower() → True; '1234'.islower() → False |
isupper() | At least one uppercase letter exists and no lowercase letter exists. Non-letters are allowed. | 'HELLO ??'.isupper() → True; '1234'.isupper() → False |
isspace() | String is non-empty and all characters are whitespace: space, tab, newline or carriage return. | ' \\n\\t '.isspace() → True |
istitle() | String is non-empty and in title case. | 'Hello World!'.istitle() → True; 'hello World!'.istitle() → False |
Whitespace removal
| Method | Purpose | Example → result |
|---|---|---|
lstrip() | Removes whitespace from left side only. | ' Hello '.lstrip() → 'Hello ' |
rstrip() | Removes whitespace from right side only. | ' Hello '.rstrip() → ' Hello' |
strip() | Removes whitespace from both ends. | ' Hello '.strip() → 'Hello' |
Replacing, joining, partitioning and splitting
| Method / syntax | Description | Example → result |
|---|---|---|
s.replace(old,new) | Returns a new string with old occurrences replaced by new. | 'Hello World!'.replace('o','*') → 'Hell* W*rld!' |
separator.join(iterable) | Joins strings, placing separator between items. | '-'.join('Hello') → 'H-e-l-l-o' |
s.partition(sep) | Returns a 3-item tuple: before first separator, separator, after. If absent, returns original and two empty strings. | 'India is Great'.partition('is') → ('India ','is',' Great') |
s.split([sep]) | Returns a list of pieces. With no separator, splits on whitespace. | 'India is a Great Country'.split() → ['India','is','a','Great','Country'] |
Examples
'-'.join('Hello')
# 'H-e-l-l-o'
text = 'India is a Great Country'
text.partition('is')
# ('India ', 'is', ' a Great Country')
text.partition('are')
# ('India is a Great Country', '', '')
text.split()
# ['India', 'is', 'a', 'Great', 'Country']
text.split('a')
# ['Indi', ' is ', ' Gre', 't Country']find() returns -1 if absent; index() raises ValueError. split() vs join(): split converts a string to a list; join combines strings into one string.8.6 Handling Strings
This section uses user-defined functions to perform operations on strings. The five textbook programs (8-1 to 8-5) are explained below.
Program 8-1: Count occurrences of a character
Task: Count how many times a character passed as an argument occurs in a given string.
def charCount(ch, st):
count = 0
for character in st:
if character == ch:
count += 1
return count
st = input("Enter a string: ")
ch = input("Enter the character to be searched: ")
count = charCount(ch, st)
print("Number of times character", ch,
"occurs in the string is:", count)Sample outputEnter a string: Today is a Holiday
Enter the character to be searched: a
Number of times character a occurs in the string is: 3charCount(ch, st)receives the target character and the string.count = 0initialises the counter.- The for loop visits every character.
- The if statement checks for a match.
count += 1increments the counter for each match.return countsends the final count to the caller.
The comparison is case-sensitive: lowercase a and uppercase A are different.
Program 8-2: Replace vowels with *
Task: Replace all vowels in a string with an asterisk.
def replaceVowel(st):
newstr = ''
for character in st:
if character in 'aeiouAEIOU':
newstr += '*'
else:
newstr += character
return newstr
st = input("Enter a String: ")
st1 = replaceVowel(st)
print("The original String is:", st)
print("The modified String is:", st1)Sample outputEnter a String: Hello World
The original String is: Hello World
The modified String is: H*ll* W*rldLogic: Start with an empty result. For each character, test membership in the lowercase and uppercase vowel string. Append * for a vowel; otherwise append the original character. Return the new string. The original remains unchanged.
Program 8-3: Print a string in reverse without creating a new string
Task: Input a string and print it in reverse without storing a reversed copy.
st = input("Enter a string: ")
for i in range(-1, -len(st)-1, -1):
print(st[i], end='')Sample outputEnter a string: Hello World
dlroW olleHLogic: Start at index -1 (last character), move backwards with step -1, and continue far enough to include the leftmost character. end='' prints characters on one line.
Program 8-4: Reverse a string and return a new string
Task: Receive a string, reverse it and store the reversed text in a new string.
def reverseString(st):
newstr = ''
length = len(st)
for i in range(-1, -length-1, -1):
newstr += st[i]
return newstr
st = input("Enter a String: ")
st1 = reverseString(st)
print("The original String is:", st)
print("The reversed String is:", st1)Sample outputEnter a String: Hello World
The original String is: Hello World
The reversed String is: dlroW olleHLogic: Create an empty string, traverse the original from last character to first, append each character to the new string, then return it. Shortcut: st[::-1].
Program 8-5: Check whether a string is a palindrome
A palindrome reads the same forwards and backwards. The textbook example is kanak.
def checkPalin(st):
i = 0
j = len(st) - 1
while i <= j:
if st[i] != st[j]:
return False
i += 1
j -= 1
return True
st = input("Enter a String: ")
result = checkPalin(st)
if result == True:
print("The given string", st, "is a palindrome")
else:
print("The given string", st, "is not a palindrome")Output 1Enter a String: kanak
The given string kanak is a palindromeOutput 2Enter a String: computer
The given string computer is not a palindromeDry run for “kanak”
| Iteration | i | j | Comparison | Action |
|---|---|---|---|---|
| 1 | 0 | 4 | k == k | Move inward |
| 2 | 1 | 3 | a == a | Move inward |
| 3 | 2 | 2 | n == n | Move inward |
| End | 3 | 1 | i > j | Return True |
ipoints to the first character;jpoints to the last.- Compare characters at both ends.
- If they differ, return
Falseimmediately. - If they match, increment
iand decrementj. - If all pairs match, return
True.
Kanak is not equal to kanak under this exact function.Chapter Summary
- A string is a sequence of characters enclosed in single, double or triple quotes.
- Indexing accesses individual characters. Positive indices range from 0 to n−1; negative indices range from −n to −1.
- Strings are immutable and cannot be changed after creation.
inandnot intest substring membership.- Slicing retrieves a portion of a string. In
s[n:m], n is included and m is excluded. - Strings can be traversed using for or while loops.
- Python provides built-in functions and string methods for manipulation.
Quick syntax reference
| Task | Syntax |
|---|---|
| Create | s = 'Python' |
| Index | s[0], s[-1] |
| Length | len(s) |
| Concatenate / repeat | s1 + s2 / s * 3 |
| Membership | 'Py' in s |
| Slicing | s[start:stop:step] |
| Reverse | s[::-1] |
| Traverse | for ch in s: |
| Case conversion | s.lower(), s.upper(), s.title() |
| Search | s.find(x), s.index(x), s.count(x) |
| Whitespace | s.lstrip(), s.rstrip(), s.strip() |
| Split / join | s.split() / '-'.join(items) |
Textbook Exercise – Worked Answers
These questions are from the uploaded chapter's Exercise section (printed pages 187–188).
Exercise 1: mySubject
mySubject = "Computer Science"mySubject[0:len(mySubject)]→ Computer Science (complete string).mySubject[-7:-1]→ Scienc (stop -1 excluded).mySubject[::2]→ Cmue cec (every second character from start).mySubject[len(mySubject)-1]→ e (last character).2*mySubject→ Computer ScienceComputer Science.mySubject[::-2]→ eniSrtpo (every second character in reverse).mySubject[:3] + mySubject[3:]→ Computer Science.mySubject.swapcase()→ cOMPUTER sCIENCE.mySubject.startswith('Comp')→ True.mySubject.isalpha()→ False, because it contains a space.
Exercise 2: myAddress
myAddress = "WZ-1,New Ganga Nagar,New Delhi"myAddress.lower()→ wz-1,new ganga nagar,new delhi.myAddress.upper()→ WZ-1,NEW GANGA NAGAR,NEW DELHI.myAddress.count('New')→ 2.myAddress.find('New')→ 5.myAddress.rfind('New')→ 21.myAddress.split(',')→['WZ-1', 'New Ganga Nagar', 'New Delhi'].myAddress.split(' ')→['WZ-1,New', 'Ganga', 'Nagar,New', 'Delhi'].myAddress.replace('New','Old')→ WZ-1,Old Ganga Nagar,Old Delhi.myAddress.partition(',')→('WZ-1', ',', 'New Ganga Nagar,New Delhi').myAddress.index('Agra')→ raisesValueError: substring not found, because Agra is absent.
Programming Problems – Model Solutions
The five programming problems below appear at the end of the chapter on printed page 188. Model solutions are provided for practice.
1. Count characters, alphabets, digits, special symbols and words
Read lines until Enter is pressed on an empty line. Count all characters (including spaces), alphabets, digits, special symbols and words.
lines = []
print("Enter text. Press Enter on a blank line to finish.")
while True:
line = input()
if line == "":
break
lines.append(line)
text = "\n".join(lines)
characters = len(text)
alphabets = digits = special = 0
for ch in text:
if ch.isalpha():
alphabets += 1
elif ch.isdigit():
digits += 1
elif not ch.isspace():
special += 1
words = len(text.split())
print("Total characters:", characters)
print("Total alphabets:", alphabets)
print("Total digits:", digits)
print("Total special symbols:", special)
print("Total words:", words)Explanation: len() counts every character, including spaces and newline separators between lines. isalpha() tests letters, isdigit() tests digits, and non-whitespace characters that are neither are counted as special symbols. split() creates the word list.
2. Convert a multi-word string into title case
def toTitleCase(st):
return st.title()
text = input("Enter a sentence: ")
print("Title case:", toTitleCase(text))The string is passed as a parameter; title() returns a title-cased string.
3. deleteChar(): delete all occurrences of a character
def deleteChar(st, ch):
newstr = ""
for character in st:
if character != ch:
newstr += character
return newstr
text = input("Enter a string: ")
ch = input("Enter character to delete: ")
if len(ch) == 1:
print(deleteChar(text, ch))
else:
print("Enter exactly one character.")Copy each character into a new string only when it is not equal to the character being deleted. Return the new string.
4. Sum digits present in a string
def sumDigits(st):
total = 0
for ch in st:
if ch.isdigit():
total += int(ch)
return total
text = input("Enter a string containing digits: ")
print("Sum of digits:", sumDigits(text))Example: abc12x4 gives 1 + 2 + 4 = 7.
5. Replace each blank space with a hyphen
def replaceBlanks(sentence):
return sentence.replace(" ", "-")
text = input("Enter a sentence: ")
print("Modified sentence:", replaceBlanks(text))Example: Python is easy to learn becomes Python-is-easy-to-learn.
Important Exam Points and Common Errors
- Positive indexing starts at 0; negative indexing starts at -1 from the right.
- Out-of-range indexing causes
IndexError; a float index causesTypeError. - Strings are immutable. Do not assign to
s[index]. - In slicing, the stop index is excluded.
- String membership and searches are case-sensitive.
find()returns -1 if not found;index()raises ValueError.lstrip(),rstrip()andstrip()remove whitespace from left, right and both ends.split()returns a list;join()returns a string.- Use
end=''to print traversed characters on the same line. - In while-loop traversal, update the index to avoid an infinite loop.
TEXTBOOK SOLUTION
Step-by-step solved textbook exercises, derivations, and solutions.
Exercise Solutions Being Updated
Step-by-step verified exercise solutions are currently being uploaded.
IMPORTANT QUESTION
High-yield board questions, previous year questions (PYQs), and model answer keys.
Important Questions Being Compiled
Board blueprint and previous years' exam questions for this chapter will be live soon.