Skip to content
Computer ScienceCBSE Class 11 · Chapter 7

Strings Class 11: Indexing, Slicing, Operations and String Methods in Python

Updated 14 October 2026 · Fact-checked

A string in Python is an immutable sequence of characters in quotes. In CBSE Class 11 Computer Science you learn indexing with positive and negative indices, slicing, concatenation, repetition and membership, traversing a string with loops, and the built-in methods named in the syllabus, from len(), upper() and find() to strip(), replace(), join(), partition() and split().

What Strings is about

Strings is part of Unit II, Computational Thinking and Programming - 1, which carries 45 of the 70 theory marks in the school annual exam. Output questions on slicing and methods, and programs that count or change characters, are the usual pattern.

The 2026-27 syllabus lists: introduction, string operations (concatenation, repetition, membership and slicing), traversing a string using loops, and the methods len(), capitalize(), title(), lower(), upper(), count(), find(), index(), endswith(), startswith(), isalnum(), isalpha(), isdigit(), islower(), isupper(), isspace(), lstrip(), rstrip(), strip(), replace(), join(), partition(), split().

Two facts drive most answers: strings are immutable (methods return a new string and leave the original unchanged), and slices exclude the stop index. All examples below were run in Python 3.

Weightage: This chapter is part of Unit II, Computational Thinking and Programming - 1, which carries 45 of the 70 theory marks in the school annual exam together with Introduction to Problem Solving, Getting Started with Python, Flow of Control, Lists, Tuples and Dictionaries and Introduction to Python Modules.Source: CBSE Computer Science (083) syllabus 2026-27, Class XI distribution of marks, Unit II Computational Thinking and Programming - 1

Key concepts

Creating strings and indexing
NCERT section NCERT 8.1, 8.2

A string is a sequence of characters (letters, digits, spaces, symbols, any Unicode character) enclosed in single quotes, double quotes or triple quotes. Triple quotes (''' or """) allow a string to run over several lines. Python has no separate character type: a single character is a string of length 1.

Each character has an index. Positive indices run 0, 1, 2, ... from the left; negative indices run -1, -2, ... from the right, so s[-1] is the last character. For a string of length n, valid indices are 0 to n - 1 and -n to -1. An index outside this range gives an IndexError. The index must be an integer (it may be an expression like s[2 + 1]).

Worked example

For s = 'PYTHON', give s[0], s[5], s[-1], s[-6], s[len(s) - 2], and say what s[6] does.

Try it first, then show the solutionSolution
  1. Indices 0-5: P Y T H O N; negative -6 to -1.
  2. s[0] = 'P', s[5] = 'N', s[-1] = 'N', s[-6] = 'P', s[4] = 'O'.
  3. s[6] is beyond the last index 5.

Answer: 'P', 'N', 'N', 'P', 'O'; s[6] raises IndexError.

Strings are immutable
NCERT section NCERT 8.2.2

Once a string is created, its characters cannot be changed in place. s[0] = 'J' gives a TypeError ('str' object does not support item assignment). To 'change' a string, build a new one, for example by slicing and concatenation, and assign it to the variable: s = 'J' + s[1:]. Every string method that seems to modify a string, such as upper() or replace(), actually returns a new string; the original stays the same unless you assign the result back.

Worked example

Give the output:

s = 'mango'
s.upper()
print(s)
t = s.upper()
print(t, s)
s = 'T' + s[1:]
print(s)
Try it first, then show the solutionSolution
  1. s.upper() returns 'MANGO' but the result is not stored; s is still 'mango'.
  2. t stores 'MANGO'; s unchanged.
  3. A new string 'T' + 'ango' is assigned to s.

Answer: mango
MANGO mango
Tango

Concatenation, repetition and membership
NCERT section NCERT 8.3.1-8.3.3
  • Concatenation + joins two strings: 'Good' + 'Day' = 'GoodDay'. Both sides must be strings; 'Age' + 15 is a TypeError.
  • Repetition * repeats a string an integer number of times: 'ab' * 3 = 'ababab'; a count of 0 or less gives the empty string ''.
  • Membership in and not in test whether one string occurs as a substring of another: 'yth' in 'Python' is True; 'P' in 'python' is False (case-sensitive).

Strings can also be compared with ==, <, > and so on, character by character using character codes (uppercase letters come before lowercase).

Worked example

Give the output: print('Na' * 2 + ' ' + 'Batman', 'bat' in 'Batman', '' in 'abc', 'Z' < 'a')

Try it first, then show the solutionSolution
  1. 'NaNa' + ' ' + 'Batman' = 'NaNa Batman'.
  2. 'bat' is not in 'Batman' because of the capital B: False.
  3. The empty string is a substring of every string: True.
  4. 'Z' (90) < 'a' (97): True.

Answer: NaNa Batman False True True

Slicing
NCERT section NCERT 8.3.4

A slice s[start:stop:step] gives a new string from index start up to but not including stop, taking every step-th character.

  • Missing start means from the beginning (or from the end if step is negative); missing stop means to the end (or the beginning if step is negative); step defaults to 1.
  • Indices may be negative: s[-3:] gives the last three characters.
  • Slicing never gives an IndexError: out-of-range indices are cut to the string's ends, and an impossible range gives ''.
  • s[::-1] reverses the string.
  • len(s[a:b]) = b - a when 0 ≤ a ≤ b ≤ len(s).

Worked example

For s = 'COMPUTER', find s[1:4], s[:3], s[4:], s[::2], s[-3:], s[::-1], s[5:2], s[2:100].

Try it first, then show the solutionSolution
  1. Indices: C0 O1 M2 P3 U4 T5 E6 R7.
  2. s[1:4] = 'OMP'; s[:3] = 'COM'; s[4:] = 'UTER'.
  3. s[::2] = C, M, U, E = 'CMUE'; s[-3:] = 'TER'; s[::-1] = 'RETUPMOC'.
  4. s[5:2] = '' (start after stop with step 1); s[2:100] = 'MPUTER' (stop cut to the end).

Answer: 'OMP', 'COM', 'UTER', 'CMUE', 'TER', 'RETUPMOC', '', 'MPUTER'

Traversing a string
NCERT section NCERT 8.4

Traversing means visiting every character, one at a time. Two ways:

  • by character: for ch in s: ... (simplest when the position is not needed)
  • by index: for i in range(len(s)): ... use s[i] (needed when the position matters, e.g. comparing s[i] with s[i + 1] or printing positions). A while loop with an index i from 0 to len(s) - 1 also works.

Traversal is the basis of counting vowels, digits or words, building a new string character by character, and checking palindromes.

Worked example

Write a program to count vowels, consonants, digits and other characters in 'CBSE 2027: Class XI'.

Try it first, then show the solutionSolution
  1. s = 'CBSE 2027: Class XI'
    v = c = d = o = 0
    for ch in s:
        if ch.isalpha():
            if ch.lower() in 'aeiou':
                v += 1
            else:
                c += 1
        elif ch.isdigit():
            d += 1
        else:
            o += 1
    print(v, c, d, o)
  2. Letters: C B S E C l a s s X I → vowels E, a, I = 3; consonants 8. Digits 2, 0, 2, 7 = 4. Others: 3 spaces and a colon = 4.

Answer: 3 8 4 4

Case and counting methods
NCERT section NCERT 8.5, Table 8.2
  • len(s): number of characters (a built-in function, not a method).
  • s.capitalize(): first character uppercase, all the rest lowercase: 'hELLO wORLD' → 'Hello world'.
  • s.title(): first letter of every word uppercase, the rest lowercase: 'hELLO wORLD' → 'Hello World'.
  • s.lower() / s.upper(): all letters to lowercase / uppercase.
  • s.count(sub[, start[, end]]): number of non-overlapping occurrences of sub: 'banana'.count('an') = 2; 'aaaa'.count('aa') = 2.
  • s.startswith(sub) / s.endswith(sub): True if s begins / ends with sub.

Worked example

s = 'india is my COUNTRY'. Give s.capitalize(), s.title(), s.upper().count('I'), s.endswith('try'), s.startswith('India').

Try it first, then show the solutionSolution
  1. capitalize: 'India is my country' (rest lowered).
  2. title: 'India Is My Country'.
  3. Uppercase 'INDIA IS MY COUNTRY' has I at 'INDIA' (2) and 'IS' (1): 3.
  4. s ends with 'TRY' in capitals, so endswith('try') is False; startswith('India') is False (s starts with 'india').

Answer: 'India is my country', 'India Is My Country', 3, False, False

Searching: find() and index()
NCERT section NCERT 8.5
  • s.find(sub[, start[, end]]) returns the lowest index where sub begins, searching s[start:end]; it returns -1 if sub is not found.
  • s.index(sub[, start[, end]]) does the same but raises a ValueError if sub is not found.

To find a later occurrence, start the search after the previous one: s.find(sub, previous + 1).

Worked example

s = 'abracadabra'. Find s.find('a'), s.find('a', 1), s.find('bra'), s.find('bra', 2), s.find('z'), and what s.index('z') does.

Try it first, then show the solutionSolution
  1. First 'a' at 0; searching from 1, next 'a' at 3.
  2. 'bra' at 1; searching from 2, next 'bra' at 8.
  3. 'z' is absent: find gives -1, index raises ValueError.

Answer: 0, 3, 1, 8, -1; s.index('z') raises ValueError.

Testing methods (is...)
NCERT section NCERT 8.5

These return True or False. For an empty string all of them return False.

  • isalnum(): every character is a letter or digit (no spaces or symbols).
  • isalpha(): every character is a letter.
  • isdigit(): every character is a digit.
  • islower() / isupper(): there is at least one letter and all letters are lowercase / uppercase (digits and symbols are ignored): 'abc12'.islower() is True.
  • isspace(): every character is whitespace (space, tab, newline).

Worked example

Give the results: 'Class11'.isalnum(), 'Class 11'.isalnum(), '2027'.isdigit(), '20.27'.isdigit(), 'HELLO 1'.isupper(), ' '.isspace(), ''.isalpha()

Try it first, then show the solutionSolution
  1. 'Class11' has only letters and digits: True; the space in 'Class 11' makes it False.
  2. '2027' True; '.' makes '20.27' False.
  3. 'HELLO 1' has letters, all uppercase: True.
  4. ' ' is all spaces: True; the empty string gives False.

Answer: True, False, True, False, True, True, False

Stripping, replacing, joining and splitting
NCERT section NCERT 8.5
  • strip(), lstrip(), rstrip(): remove whitespace from both ends, the left end only, or the right end only. Given characters as an argument, they remove any of those characters from the ends: 'xxhixx'.strip('x') = 'hi'. Characters in the middle are never removed.
  • s.replace(old, new): a new string with every occurrence of old replaced by new.
  • sep.join(iterable): joins the strings of a list, tuple or string with sep between them: '-'.join(['10', '06', '2027']) = '10-06-2027'; '*'.join('abc') = 'a*b*c'. All items must be strings.
  • s.partition(sep): splits at the first occurrence of sep into a tuple of three: (before, sep, after). If sep is not found: (s, '', '').
  • s.split(sep): returns a list of the parts. With no argument it splits on any run of whitespace and drops empty parts; with a separator it splits at each occurrence and can give empty strings: 'a,,b'.split(',') = ['a', '', 'b'].

Worked example

Give the output:

s = '  roll:25:Asha  '
t = s.strip()
print(t.split(':'))
print(t.partition(':'))
print(t.replace(':', ' | '))
print('/'.join(t.split(':')[::-1]))
Try it first, then show the solutionSolution
  1. t = 'roll:25:Asha' (spaces removed at both ends).
  2. split(':') gives three parts in a list.
  3. partition splits only at the first ':' into a 3-tuple.
  4. Every ':' replaced by ' | '.
  5. Reversed list ['Asha', '25', 'roll'] joined with '/'.

Answer: ['roll', '25', 'Asha']
('roll', ':', '25:Asha')
roll | 25 | Asha
Asha/25/roll

Strings in real life

Each concept, met in an everyday situation. Read the situation, answer the question in your own words, then compare with the model answer. The one-line hook is what to remember.

split() and join()

Suppose a school form stores a date of birth as '07/03/2009' and a new system needs it as '2009-03-07'.

Convert the date using split() and join().

Try it first, then show the solutionSolution
  1. '07/03/2009'.split('/') gives ['07', '03', '2009'].
  2. Reverse the list and join with '-': '-'.join(['2009', '03', '07']).

Answer: '2009-03-07'

Memory hook: split breaks a string into a list; join glues a list into a string.

Validating input with is... methods

Imagine an app asks for a 6-digit PIN code and a user types '1100 01'.

Which test rejects this input, and what condition accepts only valid PIN codes?

Try it first, then show the solutionSolution
  1. '1100 01'.isdigit() is False because of the space.
  2. Valid: len(pin) == 6 and pin.isdigit().

Answer: isdigit() rejects it; use len(pin) == 6 and pin.isdigit().

Memory hook: isdigit() is True only if every character is a digit.

Cleaning text with strip() and lower()

Suppose a quiz app compares answers, and a student types ' Delhi ' when the stored answer is 'delhi'.

Why does a direct comparison fail, and how should the app compare?

Try it first, then show the solutionSolution
  1. ' Delhi ' == 'delhi' is False: extra spaces and a capital D.
  2. Compare answer.strip().lower() == 'delhi', which is True.

Answer: Strip spaces and lower the case before comparing.

Memory hook: Clean first, compare second.

Topics in this chapter

Strings: syntax and key facts

Indices
0 to n-1 from the left; -1 to -n from the right; s[-k] = s[n-k]
s[n] is an IndexError.
Slice
s[start:stop:step], stop excluded; s[::-1] reverses
Slices never raise IndexError.
Operators
+ joins, * repeats (int count), in / not in test substrings
Comparison is by character codes; 'A' < 'a'.
Search
  1. 1.find()
  2. 2.index or -1; index()
  3. 3.index or ValueError; count()
  4. 4.non-overlapping occurrences
All take optional start and end.
Split and join
  1. 1.s.split(sep)
  2. 2.list; sep.join(list)
  3. 3.str; s.partition(sep)
  4. 4.3-tuple
split() with no argument splits on whitespace.
Case
capitalize(): first upper, rest lower; title(): each word capitalised; upper(); lower()
Methods return new strings.

How the school exam asks Strings

The question patterns to expect, and the method that works for each.

Question typeHow it is askedMethod
Slicing outputsGiven a string, find several slices including negative indices and steps (1-3 marks).Write the index table above and below the string first.
Method outputsOutput of a chain such as s.strip().title().split() or find() with a start (2-3 marks).Apply one method at a time and write the intermediate string; watch the type (str, list or tuple) of each result.
Error identificationWhy does s[0] = 'x' fail? Why does 'Age' + 15 fail? (1-2 marks)Immutability gives TypeError; mixing str and int gives TypeError; a missing substring in index() gives ValueError.
Programs on traversalCount vowels/words/uppercase letters, reverse each word, check a palindrome, change case, remove spaces (3-5 marks).Loop over characters (or split into words), test with is... methods, build the result in a new string.
Compare methodsDifferentiate find() and index(), split() and partition(), capitalize() and title() (2 marks).One line each on what is returned and what happens when the separator is missing.

Tricks to remember Strings

Short memory aids. Say each one aloud once, then use it on a question the same day.

  • Stop is not served

    In a slice the stop index is never included, just as range() never reaches stop.

    Use it when: Every slicing question.

  • find is friendly, index is strict

    find() quietly gives -1; index() complains with ValueError.

    Use it when: find versus index.

  • Partition = 3 parts, split = list

    partition() always returns a 3-tuple; split() returns a list of any length.

    Use it when: Output type questions.

  • Capitalise once, title every word

    capitalize() fixes the first letter of the whole string; title() fixes every word.

    Use it when: Case-method outputs.

  • Methods give new strings

    Strings never change; catch the result in a variable.

    Use it when: Questions where a method's result is not stored.

Strings: exam-level solved questions

Ordered from exam level to HOTS. Cover the solution, write your own, then compare step by step.

Example 1: Slices with negative steps · 2 marks · Short answerHarder exam level

For s = 'EXAMINATION', give s[-1:-6:-2], s[8:2:-3], s[:-4:3].

Try it first, then show the solutionSolution
  1. Indices: E0 X1 A2 M3 I4 N5 A6 T7 I8 O9 N10.
  2. s[-1:-6:-2]: indices 10, 8, 6 → 'N', 'I', 'A' = 'NIA' (stop -6 is index 5, excluded).
  3. s[8:2:-3]: 8, 5 → 'I', 'N' = 'IN' (next would be 2, excluded).
  4. s[:-4:3]: stop -4 is index 7 (excluded): 0, 3, 6 → 'E', 'M', 'A' = 'EMA'.

Answer: 'NIA', 'IN', 'EMA'

Example 2: Method chain · 2 marks · Short answerExam level

Give the output:

s = '  learn PYTHON daily  '
print(s.strip().capitalize())
print(s.split())
print(s.strip().upper().count('N'))
Try it first, then show the solutionSolution
  1. strip gives 'learn PYTHON daily'; capitalize gives 'Learn python daily'.
  2. split() on whitespace: ['learn', 'PYTHON', 'daily'].
  3. 'LEARN PYTHON DAILY' has N in LEARN and PYTHON: 2.

Answer: Learn python daily
['learn', 'PYTHON', 'daily']
2

Example 3: All positions of a substring · 3 marks · Short answerHarder exam level

Write a program to print every index at which 'ss' occurs in 'Mississippi missing' using find() with a start argument.

Try it first, then show the solutionSolution
  1. s = 'Mississippi missing'
    pos = s.find('ss')
    while pos != -1:
        print(pos, end=' ')
        pos = s.find('ss', pos + 1)
  2. 'ss' at 2 and 5 in Mississippi, and at 14 in missing.

Answer: 2 5 14

Example 4: Reverse each word · 3 marks · Short answerHarder exam level

Write a program to reverse each word of 'Practice makes perfect' but keep the word order.

Try it first, then show the solutionSolution
  1. s = 'Practice makes perfect'
    words = s.split()
    out = []
    for w in words:
        out.append(w[::-1])
    print(' '.join(out))

Answer: ecitcarP sekam tcefrep

Example 5: Toggle case without swapcase · 3 marks · Short answerHOTS / competency

Write a program that changes uppercase letters to lowercase and lowercase to uppercase in 'Hello World 2027!', leaving other characters unchanged.

Try it first, then show the solutionSolution
  1. s = 'Hello World 2027!'
    r = ''
    for ch in s:
        if ch.isupper():
            r += ch.lower()
        elif ch.islower():
            r += ch.upper()
        else:
            r += ch
    print(r)
  2. A new string is built because strings cannot be changed in place.

Answer: hELLO wORLD 2027!

Example 6: Email username and domain · 2 marks · Short answerHarder exam level

For e = 'asha.k@school.edu.in', use partition() to print the username and the domain, and use endswith() to check whether it is an Indian address.

Try it first, then show the solutionSolution
  1. e = 'asha.k@school.edu.in'
    user, at, domain = e.partition('@')
    print(user, domain, e.endswith('.in'))
  2. partition gives ('asha.k', '@', 'school.edu.in'), unpacked into three names.

Answer: asha.k school.edu.in True

Example 7: Is it a valid password? · 3 marks · Short answerHOTS / competency

A password is valid if it has at least 8 characters, at least one digit, at least one uppercase letter and no spaces. Write a program to test 'Exam2027' and 'exam 2027X'.

Try it first, then show the solutionSolution
  1. for p in ['Exam2027', 'exam 2027X']:
        digit = upper = False
        for ch in p:
            if ch.isdigit():
                digit = True
            if ch.isupper():
                upper = True
        ok = len(p) >= 8 and digit and upper and ' ' not in p
        print(p, ok)
  2. 'Exam2027': 8 characters, digit, uppercase E, no space → True. 'exam 2027X' has a space → False.

Answer: Exam2027 True
exam 2027X False

Example 8: Word frequency of one word · 2 marks · Short answerExam level

Give the output: s = 'to be or not to be'; print(s.count('to'), s.split().count('be'), s.find('be', 4), s.index('not'))

Try it first, then show the solutionSolution
  1. 'to' occurs at 0 and 13: 2. The list ['to', 'be', 'or', 'not', 'to', 'be'] has 'be' twice: 2.
  2. Searching from index 4: next 'be' at 16. 'not' starts at 9.

Answer: 2 2 16 9

Case-study practice (Section E style)

Read the situation, then answer every part. In a school exam set on the board pattern this is a 4-mark question split into 1 + 2 + 1 marks.

Generating student usernames

Suppose a school creates a username for each student from the full name and roll number: the first letter of the first name, the full surname, and the roll number, all in lowercase, e.g. 'Riya Sharma', 23 → 'rsharma23'. Names are typed by different staff, so some have extra spaces or odd capitals such as ' aMAN verma '.

  1. (i) · 1 mark

    Which methods clean ' aMAN verma ' into ['aman', 'verma']?

    Answer

    Answer: name.lower().split() (split() with no argument also handles the extra spaces).

    lower() fixes case; split() drops the extra whitespace.

  2. (ii) · 2 marks

    Write the code to make the username for ' aMAN verma ' with roll 7.

    Answer

    Answer:

    name = '  aMAN   verma '
    roll = 7
    parts = name.lower().split()
    user = parts[0][0] + parts[-1] + str(roll)
    print(user)
    Output: averma7

    parts[0][0] is the first letter of the first name; parts[-1] the surname; str() is needed to join the roll number.

  3. (iii) · 1 mark

    Two students get the same username 'averma7'? Suggest a check using a string method on a list of existing names.

    Answer

    Answer: Before saving, test if user in existing (a list); if so, add a suffix, e.g. user + 'b'. Membership with in, then concatenation.

    in works on lists of strings as well as on strings.

Where the marks are

How a typical answer is split into step marks. Show every step: a right final answer alone rarely earns full marks.

Differentiate between find() and index() with an example. [2 marks] (2 marks)

StepMarks
Both return the lowest index of the substring; find() returns -1 if it is absent1
index() raises ValueError if absent; example 'abc'.find('z') = -1, 'abc'.index('z') → ValueError1

Write a program to input a sentence and print the number of words that start with a vowel. [3 marks] (3 marks)

StepMarks
Input the sentence and split it into words with split()1
Loop over words, test word[0].lower() in 'aeiou' and count1.5
Print the count0.5

Write a program to input a sentence and (i) print it with the first letter of each word in uppercase without using title(), (ii) print the longest word, and (iii) check whether the sentence (ignoring spaces and case) is a palindrome. [5 marks] (5 marks)

StepMarks
Input and split into words0.5
(i) Build each word as w[0].upper() + w[1:] and join with ' '1.5
(ii) Track the longest word in a loop using len()1.5
(iii) t = s.replace(' ', '').lower(); compare t with t[::-1]1
Clear output for each part0.5

Where students lose marks in Strings

The slips examiners see most often, and what to write instead.

  • Mistake: Expecting a method to change the string in place

    Strings are immutable; methods return new strings.

    Wrong working

    s = 'hi'
    s.upper()
    print(s) → HI

    Right working

    s = 'hi'
    s.upper()
    print(s) → hi; use s = s.upper()

    Do this: Assign the result back if you need it.

    Usually costs: 1 mark

  • Mistake: Including the stop character in a slice

    s[a:b] ends at index b - 1.

    Wrong working

    'PYTHON'[1:4] = 'YTHO'

    Right working

    'PYTHON'[1:4] = 'YTH'

    Do this: Count b - a characters from index a.

    Usually costs: 1 mark

  • Mistake: Thinking capitalize() keeps the rest of the string

    capitalize() lowers every other character.

    Wrong working

    'python IS fun'.capitalize() = 'Python IS fun'

    Right working

    'Python is fun'

    Do this: Remember the rest is lowered.

    Usually costs: 1 mark

  • Mistake: Writing the separator as an argument of join()

    join() is called on the separator and takes the list.

    Wrong working

    ['a', 'b'].join('-')

    Right working

    '-'.join(['a', 'b'])

    Do this: separator.join(list).

    Usually costs: 1 mark

  • Mistake: Assuming strip() removes spaces inside the string

    strip() works only at the two ends.

    Wrong working

    ' a b '.strip() = 'ab'

    Right working

    ' a b '.strip() = 'a b'; use replace(' ', '') to remove all spaces

    Do this: Ends only: strip; everywhere: replace.

    Usually costs: 1 mark

NCERT exercise guide: Strings

What each exercise in the NCERT chapter tests, how to approach it, and a question of the same kind solved step by step. Questions here are written in our own words.

NCERT Chapter 8 exercise: outputs of string operations and methods

What it tests: Slicing, operators and methods on given strings.

How to approach it: Write the index table; apply one operation at a time; give the exact output with quotes where Python shows them (inside lists and tuples).

Same kind as the 'give the output of the following' question

sub = 'Data Science'. Give: sub[0:len(sub)], sub[-7:-1], sub[::2], sub[len(sub)-1], 2*sub[:3], sub.split('a').

Show the solutionSolution
  1. Whole string: 'Data Science' (12 characters).
  2. The last 7 characters are 'Science'; [-7:-1] stops before the last: 'Scienc'.
  3. Every second character from index 0: D, t, space, c, e, c → 'Dt cec'.
  4. Last character 'e'; 'Dat' repeated: 'DatDat'.
  5. Split at each 'a': ['D', 't', ' Science'].

Answer: 'Data Science', 'Scienc', 'Dt cec', 'e', 'DatDat', ['D', 't', ' Science']

NCERT Chapter 8 exercise: string programs

What it tests: Counting characters, replacing, reversing words, checking palindromes, case conversion.

How to approach it: Traverse with a for loop or split into words; use the is... methods for tests; build results in a new string because strings are immutable.

Same kind as the 'replace each space with a hyphen' program

Write a program that replaces every space in 'Save Water Save Life' with '-' without using replace(), and also with replace().

Show the solutionSolution
  1. s = 'Save Water Save Life'
    r = ''
    for ch in s:
        if ch == ' ':
            r += '-'
        else:
            r += ch
    print(r)
    print(s.replace(' ', '-'))

Answer: Save-Water-Save-Life
Save-Water-Save-Life

Practice questions on Strings

Write each answer on paper first. Open the hint only if you are stuck, and the answer only when you have finished.

  1. Q1 · 1 mark · MCQExam level

    What is the output of print('Python'[2:5])? (a) yth (b) tho (c) thon (d) ytho

    Hint

    Indices 2, 3, 4.

    Answer

    (b) tho

  2. Q2 · 1 mark · Very short answerExam level

    Give the output of 'abc'.upper().isupper(), 'ABC1'.isalpha(), 'a-b-c'.split('-').

    Hint

    isalpha rejects digits.

    Answer

    True False ['a', 'b', 'c']

  3. Q3 · 2 marks · Short answerHarder exam level

    Predict the output:

    s = 'GOOD MORNING'
    print(s.partition(' '), s.partition('X'))
    Hint

    Separator not found.

    Answer

    ('GOOD', ' ', 'MORNING') ('GOOD MORNING', '', '')

  4. Q4 · 2 marks · Short answerExam level

    Why does the following give an error? Correct it.
    s = 'tool'
    s[0] = 'c'

    Hint

    Immutability.

    Answer

    Strings are immutable, so item assignment raises TypeError. Correct: s = 'c' + s[1:] (gives 'cool').

  5. Q5 · 2 marks · Short answerHarder exam level

    Give the output of print('*'.join('2027'), '2027'.find('2', 1), '2027'.rstrip('7'))

    Hint

    join on a string uses each character.

    Answer

    2*0*2*7 2 202

  6. Q6 · 3 marks · Short answerExam level

    Write a program to count the uppercase letters, lowercase letters and spaces in 'Digital India Mission'.

    Hint

    isupper(), islower(), isspace() on each character.

    Answer

    s = 'Digital India Mission'
    u = l = sp = 0
    for ch in s:
    if ch.isupper(): u += 1
    elif ch.islower(): l += 1
    elif ch.isspace(): sp += 1
    print(u, l, sp)
    Output: 3 16 2

  7. Q7 · 1 mark · MCQHarder exam level

    Assertion (A): 'ab' in 'cab' and 'ab' in ['cab'] both give True. Reason (R): in checks substrings for a string and items for a list. Choose (a) both true, R explains A (b) both true, R does not explain A (c) A false, R true (d) both false.

    Hint

    Is 'ab' an item of ['cab']?

    Answer

    (c) A is false ('ab' in ['cab'] is False, since 'ab' is not an item of the list); R is true.

  8. Q8 · 2 marks · Short answerHarder exam level

    Predict the output:

    w = 'level'
    print(w == w[::-1], w[1:-1], w.count('l', 1))
    Hint

    Search from index 1.

    Answer

    True eve 1

  9. Q9 · 2 marks · Short answerHOTS / competency

    Write a program that prints the initials of a full name, e.g. 'Mohandas Karamchand Gandhi' → 'M.K.G.'

    Hint

    split() then take w[0].

    Answer

    name = 'Mohandas Karamchand Gandhi'
    print(''.join(w[0].upper() + '.' for w in name.split()))
    (or build the string in a loop) Output: M.K.G.

  10. Q10 · 3 marks · Short answerHOTS / competency

    Write a program that removes all vowels from 'Education is power' and prints the result and the number of vowels removed.

    Hint

    Build a new string, count separately.

    Answer

    s = 'Education is power'
    r = ''
    c = 0
    for ch in s:
    if ch.lower() in 'aeiou':
    c += 1
    else:
    r += ch
    print(r, c)
    Output: dctn s pwr 8

  11. Q11 · 2 marks · Short answerHOTS / competency

    s = 'banana'. Without running, give s.replace('a', 'o', 2) and explain the third argument.

    Hint

    Count of replacements.

    Answer

    'bonona'. The optional third argument limits how many occurrences (from the left) are replaced; here only the first two 'a's.

  12. Q12 · 1 mark · Very short answerHarder exam level

    What is the output of print(len(' a b '.strip()), len('a,b,,c'.split(',')))?

    Hint

    Empty part between the commas.

    Answer

    3 4

Test your recall

Answer in your head or on paper first, then open the card. Pulling an answer out of memory makes it stick far better than re-reading.

  1. 1.What is s[-1] for s = 'CBSE'?Show answer

    'E'.

  2. 2.What does 'abc' * 0 give?Show answer

    '' (an empty string).

  3. 3.What does find() return when the substring is absent?Show answer

    -1.

  4. 4.What type does partition() return?Show answer

    A tuple of three strings.

  5. 5.What is 'hello world'.title()?Show answer

    'Hello World'.

  6. 6.What error does s[0] = 'x' give?Show answer

    TypeError (strings are immutable).

  7. 7.What is ''.isdigit()?Show answer

    False.

  8. 8.What is 'a b c'.split()?Show answer

    ['a', 'b', 'c'].

Best order to study it

  1. Creating strings; positive and negative indexing; immutability.
  2. Operators: +, *, in, not in, comparisons.
  3. Slicing with start, stop and step; reversing.
  4. Traversing with for and with indices.
  5. Case and count methods; startswith and endswith.
  6. find and index; the is... methods.
  7. strip family, replace, join, partition, split; then practise programs.

Quick revision checklist

The night before the exam: can you do each of these without looking?

  • String: immutable sequence of characters; indices 0..n-1 and -1..-n.
  • + joins, * repeats, in tests substrings.
  • s[a:b:c] stops before b; s[::-1] reverses; slices never raise IndexError.
  • capitalize: first letter only (rest lower); title: every word.
  • find gives -1, index gives ValueError when absent.
  • is... methods are False for an empty string.
  • strip removes only from the ends; replace changes every occurrence.
  • split → list; partition → 3-tuple; sep.join(list) → string.

Strings: frequently asked questions

Is the syllabus method list complete for the exam?

The 2026-27 syllabus names len(), capitalize(), title(), lower(), upper(), count(), find(), index(), endswith(), startswith(), isalnum(), isalpha(), isdigit(), islower(), isupper(), isspace(), lstrip(), rstrip(), strip(), replace(), join(), partition() and split(). Learn what each returns and how it behaves in edge cases (empty strings, missing separators).

Why does slicing not give an IndexError?

A slice is defined as 'from here up to there'; Python cuts out-of-range limits to the ends of the string. Only single-index access such as s[10] checks the range and raises IndexError.

What is the difference between split() and split(' ')?

split() with no argument splits on any run of whitespace and ignores leading and trailing spaces. split(' ') splits at every single space, so double spaces give empty strings: 'a b'.split(' ') is ['a', '', 'b'].

How do I check whether a string is a palindrome?

Compare it with its reverse: s == s[::-1]. To ignore case and spaces, first clean it: t = s.replace(' ', '').lower(), then compare t == t[::-1].

Does count() count overlapping matches?

No. 'aaaa'.count('aa') is 2, not 3, because the search continues after each match.

Based on: CBSE Computer Science (083) syllabus, Class XI 2026-27; NCERT Computer Science, Textbook for Class XI, Chapter 8 Strings (Reprint 2026-27)