Computer Science (Python) Chapter 8 4 Study Options Available

Strings

CHAPTER PDF

Complete curriculum textbook chapter document for reading and offline study.

NOTES

Complete conceptual breakdown, formulas, diagrams, and memory aids.

Class 11 Computer Science – Chapter 8: Strings
CBSE • Class XI • Computer Science

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.

Learning outcomes: Create strings; use positive and negative indexing; slice and traverse strings; use string operators and methods; write functions to count, replace, reverse and test strings.

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"""
Use matching opening and closing quotes. Triple quotes are useful for multiline text. A one-character string such as '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 raises TypeError.

Index table: “Hello World!”

The string has 12 characters, including the space. This table corresponds to Table 8.1 on printed page 177.

CharacterHellospaceWorld!
Positive index01234567891011
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 6

str1[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])      # H
Remember: Last character = s[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)      # Hello

A 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.

in

True if the left operand occurs in the right operand; otherwise False.

not in

True 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)  # False

Membership 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])  # HlWl

Negative-index slicing

str1 = 'Hello World!'
print(str1[-6:-1])   # World

This selects indices -6, -5, -4, -3 and -2; -1 is excluded.

Reverse a string with slicing

str1 = 'Hello World!'
print(str1[::-1])    # !dlroW olleH
Exam point: The stop index is excluded in every slice. A negative step moves from right to left.

8.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 += 1

Output: Hello World!. The index ranges from 0 to len(str1)-1. It must be incremented so the condition eventually becomes false.

for loopwhile 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/functionDescriptionExample → 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

MethodDescriptionExample
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

MethodReturns 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

MethodPurposeExample → 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 / syntaxDescriptionExample → 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() vs index(): Both search for a substring. 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 output
Enter a string: Today is a Holiday
Enter the character to be searched: a
Number of times character a occurs in the string is: 3
  1. charCount(ch, st) receives the target character and the string.
  2. count = 0 initialises the counter.
  3. The for loop visits every character.
  4. The if statement checks for a match.
  5. count += 1 increments the counter for each match.
  6. return count sends 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 output
Enter a String: Hello World
The original String is: Hello World
The modified String is: H*ll* W*rld

Logic: 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 output
Enter a string: Hello World
dlroW olleH

Logic: 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 output
Enter a String: Hello World
The original String is: Hello World
The reversed String is: dlroW olleH

Logic: 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 1
Enter a String: kanak
The given string kanak is a palindrome
Output 2
Enter a String: computer
The given string computer is not a palindrome

Dry run for “kanak”

IterationijComparisonAction
104k == kMove inward
213a == aMove inward
322n == nMove inward
End31i > jReturn True
  1. i points to the first character; j points to the last.
  2. Compare characters at both ends.
  3. If they differ, return False immediately.
  4. If they match, increment i and decrement j.
  5. If all pairs match, return True.
The textbook program is case-sensitive and includes spaces and punctuation in comparisons. Thus 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.
  • in and not in test 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

TaskSyntax
Creates = 'Python'
Indexs[0], s[-1]
Lengthlen(s)
Concatenate / repeats1 + s2 / s * 3
Membership'Py' in s
Slicings[start:stop:step]
Reverses[::-1]
Traversefor ch in s:
Case conversions.lower(), s.upper(), s.title()
Searchs.find(x), s.index(x), s.count(x)
Whitespaces.lstrip(), s.rstrip(), s.strip()
Split / joins.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"
  1. mySubject[0:len(mySubject)] → Computer Science (complete string).
  2. mySubject[-7:-1] → Scienc (stop -1 excluded).
  3. mySubject[::2] → Cmue cec (every second character from start).
  4. mySubject[len(mySubject)-1] → e (last character).
  5. 2*mySubject → Computer ScienceComputer Science.
  6. mySubject[::-2] → eniSrtpo (every second character in reverse).
  7. mySubject[:3] + mySubject[3:] → Computer Science.
  8. mySubject.swapcase() → cOMPUTER sCIENCE.
  9. mySubject.startswith('Comp') → True.
  10. mySubject.isalpha() → False, because it contains a space.

Exercise 2: myAddress

myAddress = "WZ-1,New Ganga Nagar,New Delhi"
  1. myAddress.lower() → wz-1,new ganga nagar,new delhi.
  2. myAddress.upper() → WZ-1,NEW GANGA NAGAR,NEW DELHI.
  3. myAddress.count('New') → 2.
  4. myAddress.find('New') → 5.
  5. myAddress.rfind('New') → 21.
  6. myAddress.split(',') → ['WZ-1', 'New Ganga Nagar', 'New Delhi'].
  7. myAddress.split(' ') → ['WZ-1,New', 'Ganga', 'Nagar,New', 'Delhi'].
  8. myAddress.replace('New','Old') → WZ-1,Old Ganga Nagar,Old Delhi.
  9. myAddress.partition(',') → ('WZ-1', ',', 'New Ganga Nagar,New Delhi').
  10. myAddress.index('Agra') → raises ValueError: 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 causes TypeError.
  • 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() and strip() 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.
Study method: Write character indices above a string. For slicing, mark the stop index as excluded. For programs, trace variable values line by line before running the code.
Class XI Computer Science • Chapter 8: Strings • Responsive learning notes

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.