String Slicing and String Methods in Python (Class 12 Computer Science)
Updated 16 October 2026 · Fact-checked
A string is an immutable sequence of characters. s[start:stop:step] copies characters from start up to, but not including, stop; a negative step walks backwards. String methods such as upper(), replace(), strip(), split() and join() never change s; they return a new string or list, so the result must be printed or stored.
Understand String Slicing and String Methods
A string is a sequence of characters in quotes. Each character has a positive index (0 from the left) and a negative index (-1 from the right). In s = 'Board Exam', s[0] is 'B' and s[-1] is 'm'. Indexing past the end raises IndexError. Strings are immutable: s[0] = 'b' raises TypeError, so every 'change' builds a new string.
Slicing s[start:stop:step] takes characters from start up to stop - 1, jumping by step. Defaults: start = beginning, stop = end, step = 1. With a negative step the defaults flip (start = last character, stop = before the first) and the slice moves leftwards, so s[::-1] is the reversed string. If start is already past stop in the direction of travel, the result is the empty string ''. Slices never raise IndexError.
Operators. + joins strings, * repeats ('ab' * 3 is 'ababab'), and in tests for a substring ('Ex' in s is True). Comparison is character by character using character codes, so 'Z' < 'a'.
Methods in the syllabus, grouped by what they return:
- new string:
lower(),upper(),capitalize()(first character upper, rest lower),title()(first letter of every word upper),strip(),lstrip(),rstrip()(remove spaces at both ends, left, right),replace(old, new)(every occurrence, or only the first n with a third argument),sep.join(seq)(glues the strings of seq with sep) - number:
len(s),count(sub)(non-overlapping occurrences),find(sub)(first index, or -1 if absent),index(sub)(first index, or ValueError if absent) - True/False:
startswith(),endswith(),isalpha(),isdigit(),isalnum(),islower(),isupper(),isspace(); these give False for the empty string - list or tuple:
split(sep)returns a list; without sep it splits on runs of whitespace, with sep it cuts at every sep and leaves empty strings between two adjacent separators ('committee'.split('t')is ['commi', '', 'ee']);partition(sep)returns a 3-tuple (before, sep, after) split at the first sep only
Traversal. for ch in s: visits characters; for i in range(len(s)): gives positions. Build a result with res = res + ... because the original cannot be changed.
Recent sample papers ask a string output item every year (split with a separator, a negative-step slice, replace/find, or a loop that converts characters), so the habit to build is to write down the index table before answering.
String Slicing and String Methods: key facts
- Slicing rules
- s[a:b]: characters a to b - 1
- s[a:]: from a to the end
- s[:b]: from the start to b - 1
- s[::k]: every k-th character
- s[::-1]: reversed copy
- s[a:b:-k]: from a leftwards, stopping before b
- A slice never raises IndexError; it can be the empty string.
- Methods returning a new string
lower() / upper() change the case capitalize() first character upper, rest lower title() first letter of each word upper strip(), lstrip(), rstrip() remove spaces at both ends, left, right replace(old, new[, n]) replace all (or first n) sep.join(seq) join strings with sep - s itself never changes: write s = s.upper() to keep the result.
- Searching and counting
count(sub) non-overlapping occurrences find(sub) first index, -1 if absent index(sub) first index, ValueError if absent startswith(p), endswith(p) True or False sub in s True or False - find and index accept a start position: 'banana'.find('n', 3) is 4.
- Character tests (True/False)
isalpha() letters only isdigit() digits only isalnum() letters or digits only islower() / isupper() all cased letters lower / upper isspace() whitespace only - All give False for an empty string; 'ABC1'.isupper() is True (digits are ignored).
- split versus partition
split() list of words, cut at whitespace split(sep) list, cut at every sep; adjacent seps give '' partition(sep) tuple (before, sep, after), cut at the first sep; if sep is absent: (s, '', '') - Brackets give it away: split answers use [ ], partition answers use ( ).
How to answer String Slicing and String Methods questions
Use this routine for string output and string program questions.
- 1Write the string with its indexes underneath (positive, and negative if the code uses them). Count spaces as characters.
- 2For a slice, write the indexes visited: start, start + step, ... and stop before stop. For a negative step, start from the right if start is missing.
- 3For each method, decide what it returns: a new string, a number, True/False, a list (split) or a tuple (partition). The original string is unchanged.
- 4For split(sep), mark every occurrence of sep and write what lies between them, including empty strings.
- 5In loops that build a string, track the result after every character; check which branch (if/elif/else) each character takes.
- 6In programs, use split() to get words and len(), startswith(), isupper() and similar tests on each word.
- 7Write the output exactly: lists with quotes around each string, tuples with round brackets, and no quotes when a plain string is printed.
String Slicing and String Methods in real life
The idea, met in an everyday situation. Answer the question in your own words, then compare with the model answer. The one-line hook is what to remember.
Cleaning and checking input with strip(), lower(), endswith() and split()
Suppose a school portal accepts only school e-mail IDs ending in @dps.edu, and a student types ' Riya.Sen@DPS.edu ' with extra spaces and capital letters.
Write code to clean the input, check the domain, and print the user name part before '@'.
Try it first, then show the solutionSolution
- strip() removes the outer spaces and lower() makes the comparison case-insensitive.
raw = ' Riya.Sen@DPS.edu ' email = raw.strip().lower() if email.endswith('@dps.edu'): user = email.split('@')[0] print('Valid', user) else: print('Use your school ID')- split('@') gives ['riya.sen', 'dps.edu']; index 0 is the user name.
Answer: Valid riya.sen
Memory hook: Strip the spaces, lower the shouting, then split at the @.
Slicing to build a code
Imagine a library makes a member code from the first three letters of the surname in capitals, the last two digits of the joining year and the first letter of the first name: for 'Arjun Mehta' with joining year 2026 the code is MEH26A.
Write the code for name = 'Arjun Mehta' and year = '2026' using slicing, split() and upper().
Try it first, then show the solutionSolution
- split() gives ['Arjun', 'Mehta']; surname[:3] is 'Meh'; year[-2:] is '26'; first[0] is 'A'.
name = 'Arjun Mehta' year = '2026' first, surname = name.split() code = surname[:3].upper() + year[-2:] + first[0] print(code)
Answer: MEH26A
Memory hook: [:3] takes the front three, [-2:] takes the last two.
Tricks to remember String Slicing and String Methods
Short memory aids. Say each one aloud once, then use it on a question the same day.
Start in, stop out
In every slice, the start index is included and the stop index is left out, in either direction.
Use it when: All slicing questions.
find is friendly, index is strict
find() shrugs and returns -1 when the text is missing; index() complains with ValueError.
Use it when: MCQs on find versus index.
Strings are carved in stone
No method carves into the original; each one gives you a fresh copy you must catch with =.
Use it when: Questions where s.upper() is called but s is printed.
Square or round?
split splits into a list [ ]; partition parts into exactly three ( ).
Use it when: Writing the output of split() and partition().
String Slicing and String Methods: solved examples
Ordered from board level to HOTS. Try each one before you open the solution.
Example 1: Basic slices · 1 mark · Very short answerBoard level
Write the output:
s = 'Board Exam'
print(s[2:7], s[-4:], s[::3])Try it first, then show the solutionSolution
- Indexes: B0 o1 a2 r3 d4 (space)5 E6 x7 a8 m9.
- s[2:7] is indexes 2 to 6: 'ard E'. s[-4:] is the last four: 'Exam'. s[::3] is indexes 0, 3, 6, 9: 'BrEm'.
Answer: ard E Exam BrEm
Example 2: split() with a separator and partition() · 2 marks · Short answerHarder board level
Write the output:
print('committee'.split('t'))
print('a-b-c'.partition('-'), 'a-b-c'.partition('#'))Try it first, then show the solutionSolution
- 'committee' has two adjacent t's: c-o-m-m-i | t | t | e-e. Between them is the empty string. (1 mark)
- partition cuts at the first '-' only and returns a 3-tuple; when '#' is absent it returns (whole string, '', ''). (1 mark)
Answer: ['commi', '', 'ee']
('a', '-', 'b-c') ('a-b-c', '', '')
Example 3: A character-conversion loop · 2 marks · Short answerHarder board level
Predict the output:
code = 'Ab3#z9'
out = ''
for ch in code:
if ch.isupper():
out += ch.lower()
elif ch.isdigit():
out += str(int(ch) * 3)
elif ch.isalpha():
out += '*'
else:
out += '@'
print(out)Try it first, then show the solutionSolution
- 'A' is upper → 'a'. 'b' is a lower-case letter → '*'. '3' → '9'.
- '#' is none of these → '@'. 'z' → '*'. '9' → '27'.
Answer: a*9@*27
Example 4: Longest word · 3 marks · Short answerHarder board level
Write a function longest(sentence) that returns the longest word of a sentence and its length (the first one if there is a tie). Show the result for 'Python makes coding enjoyable'.
Try it first, then show the solutionSolution
- Split into words (1 mark), keep the longest seen so far with a strict > so the first wins a tie (1 mark), return both values (1 mark).
def longest(sentence): best = '' for w in sentence.split(): if len(w) > len(best): best = w return best, len(best) print(longest('Python makes coding enjoyable'))
Answer: ('enjoyable', 9)
Example 5: Negative steps with negative and out-of-range limits · 2 marks · Short answerHOTS / competency
Predict the output:
w = 'PROGRAMMING'
print(w[-3:2:-2], w[8:-12:-3], w[::-4])Try it first, then show the solutionSolution
- Indexes: P0 R1 O2 G3 R4 A5 M6 M7 I8 N9 G10. -3 is index 8.
- w[-3:2:-2]: 8 (I), 6 (M), 4 (R); 2 is the stop → 'IMR'. (1 mark)
- w[8:-12:-3]: -12 lies before the start of the string, so the slice runs to the beginning: 8 (I), 5 (A), 2 (O) → 'IAO'. w[::-4]: 10 (G), 6 (M), 2 (O) → 'GMO'. (1 mark)
Answer: IMR IAO GMO
Example 6: Case study: a password checker · 4 marks · Case-basedHOTS / competency
Suppose a website accepts a password only if, after removing spaces at both ends, it has at least 8 characters, at least one digit, and at least one upper-case letter.
(i) Write a function valid(p) that returns True or False. (3 marks)
(ii) A programmer tries p[0] = p[0].upper() to fix the first letter. What happens? (1 mark)
Try it first, then show the solutionSolution
- (i) Strip first, check the length, then scan for a digit and an upper-case letter:
def valid(p): p = p.strip() if len(p) < 8: return False digit = upper = False for ch in p: if ch.isdigit(): digit = True elif ch.isupper(): upper = True return digit and upper print(valid(' sunRise2026 '), valid('sunrise2026'), valid('Sun12')) - 'sunRise2026' has 11 characters, digits and an R: True. 'sunrise2026' has no capital: False. 'Sun12' is too short: False.
- (ii) Strings are immutable, so item assignment raises TypeError: 'str' object does not support item assignment. Use p = p[0].upper() + p[1:].
Answer: (i) True False False for the three calls shown (ii) TypeError; build a new string instead.
Where students lose marks in String Slicing and String Methods
The slips examiners see most often, and what to write instead.
Mistake: Leaving out the empty strings in split(sep)
Two separators next to each other have an empty string between them, and split(sep) keeps it.
Wrong working
'committee'.split('t') → ['commi', 'ee']
Right working
'committee'.split('t') → ['commi', '', 'ee']
Do this: Mark each separator and write what lies between every pair, even if it is nothing.
Usually costs: The full mark of a 1-mark MCQ.
Mistake: Expecting a method to change the string
Strings are immutable; methods return new strings.
Wrong working
s = 'cbse'
s.upper()
print(s) # CBSERight working
s = 'cbse'
s = s.upper()
print(s) # CBSEDo this: Store or print the returned value.
Usually costs: 1 mark.
Mistake: Starting a negative-step slice at the wrong end
With a negative step and no start, the slice begins at the last character.
Wrong working
'PYTHON'[:2:-1] → 'PY'
Right working
'PYTHON'[:2:-1] → 'NOH' (indexes 5, 4, 3)
Do this: For a negative step, default start = last index and move left until just before stop.
Usually costs: 1 mark.
Mistake: Writing split() output without quotes or brackets
print() of a list shows the list form, with square brackets and quotes around each string.
Wrong working
print('a b'.split()) → a b
Right working
print('a b'.split()) → ['a', 'b']
Do this: Show the exact printed form of lists and tuples.
Usually costs: Half to 1 mark.
Exam tips
- Draw the index table first; most slicing errors come from miscounting spaces.
- For 'count the words that ...' programs, split() the line or text, then test each word; for 'count the characters that ...', loop over the string itself.
- If a question wants the result to replace the original, write s = s.replace(...); a bare call loses the marks for the change.
- Use only syllabus methods in written answers (for example lower() and upper(), not swapcase()); the marking scheme is built around them.
- When a slice looks impossible (start already past stop), the answer is the empty string, which print() shows as a blank line.
Practice questions on String Slicing and String Methods
Write each answer on paper first. Open the hint only if you are stuck, and the answer only when you have finished.
Q1 · 1 mark · MCQBoard level
Which string method returns -1 when the substring is not found?
(a) index() (b) find() (c) count() (d) split()Hint
One is friendly, one is strict.
Answer
(b) find()
Q2 · 1 mark · Very short answerBoard level
Write the output:
print('Hello World'.lower().count('o'), 'abc' * 2)Hint
Count after lowering; * repeats.
Answer
2 abcabc
Q3 · 1 mark · MCQBoard level
What is 'Python'[1:4]?
(a) 'Pyt' (b) 'yth' (c) 'ytho' (d) 'thon'Hint
Start in, stop out.
Answer
(b) 'yth'
Q4 · 2 marks · Short answerHarder board level
Write the output:
print(' cbse 2026 '.strip().title(), '-'.join(['a', 'b'])) print('mississippi'.replace('ss', 'SS', 1), 'mississippi'.count('ss'))Hint
The third argument of replace limits the number of replacements.
Answer
Cbse 2026 a-b
miSSissippi 2Q5 · 3 marks · Short answerHarder board level
Write a function mask_vowels(s) that returns a new string in which every vowel (upper or lower case) of s is replaced by '*'. Show the result for 'Education'.
Hint
Strings are immutable: build a new one.
Answer
def mask_vowels(s): res = '' for ch in s: if ch.lower() in 'aeiou': res += '*' else: res += ch return res print(mask_vowels('Education'))Output: *d*c*t**n
Q6 · 1 mark · Assertion-reasonHarder board level
Assertion (A): After s = 'cbse' and s.upper(), print(s) displays CBSE.
Reason (R): Strings in Python are immutable.
(a) Both A and R are true and R is the correct explanation of A. (b) Both A and R are true but R is not the correct explanation of A. (c) A is true but R is false. (d) A is false but R is true.Hint
Was the result of upper() stored?
Answer
(d) A is false (it prints cbse, because upper() returns a new string that is not stored) but R is true.
Q7 · 2 marks · Short answerHOTS / competency
Predict what happens, line by line:
s = 'banana' print(s.find('n', 3), s.index('a', 2)) print(s.find('x')) print(s.index('x'))Hint
The second argument is where the search starts.
Answer
4 3
-1
then ValueError: substring not found (index() raises an error where find() returns -1).
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.What is 'abcdef'[::-2]?Show answer
'fdb'.
2.What does 'a,b,,c'.split(',') return?Show answer
['a', 'b', '', 'c'].
3.What does partition() return if the separator is missing?Show answer
A tuple of the whole string and two empty strings, e.g. ('abc', '', '').
4.What is the difference between capitalize() and title()?Show answer
capitalize() makes only the first character of the string upper case (the rest lower); title() capitalises the first letter of every word.
5.What does ''.isalpha() return?Show answer
False.
6.What happens on s[0] = 'X' for a string s?Show answer
TypeError: 'str' object does not support item assignment.
String Slicing and String Methods: frequently asked questions
What is the difference between find() and index() in Python?
Both return the position of the first occurrence of a substring. If the substring is absent, find() returns -1 while index() raises ValueError: substring not found.
How does slicing with a negative step work?
The slice moves from right to left. Without a start it begins at the last character, and it stops just before the stop index. For example, 'PYTHON'[::-2] gives 'NHY' (indexes 5, 3, 1).
Which string methods are in the CBSE syllabus?
len(), capitalize(), title(), lower(), upper(), count(), find(), index(), endswith(), startswith(), isalnum(), isalpha(), isdigit(), islower(), isupper(), isspace(), lstrip(), rstrip(), strip(), replace(), join(), partition() and split(), with concatenation, repetition, membership, slicing and traversal.
What is the difference between split() and partition()?
split() cuts at every separator and returns a list of any length. partition() cuts only at the first separator and always returns a tuple of three parts: the text before, the separator, and the text after.
Why can't I change one character of a string?
Strings are immutable, so s[i] = 'x' raises TypeError. Build a new string instead, for example s = s[:i] + 'x' + s[i+1:], and assign it back to s.