Skip to content
7 MIN LESSON · COMPUTER SCIENCE

Class 11 Strings: Complete Concepts and Practice

Computer Science — Creating text and understanding immutability, Length, indexing and valid boundaries, Slicing with start, stop and step, Operators, comparison and membership, Searching and counting methods, Changing appearance and testing character classes, Cleaning, splitting and joining, Traversal and a worked text algorithm.

Big picture

A string stores text as an ordered sequence of Unicode characters. Student names, postal addresses, search terms and messages are all text, even when they contain digits. Treating a roll-number string as a number can remove leading zeros that are meaningful identifiers.

Python strings support indexing, slicing, traversal and many useful methods, but they cannot be changed in place. This chapter connects each operation to the information it returns, with special attention to boundaries, missing matches and the difference between a new string and a modified original.

Learning goals

  • Explain string creation, immutability and rebinding.

  • Trace indexing, slicing and negative steps.

  • Use searching and character-test methods correctly.

  • Clean, split and join text with explicit assumptions.

  • Design vowel-count and palindrome algorithms.

Core ideas

1. Creating text and understanding immutability

A string is written with matching single or double quotes; triple quotes permit multiline literals. Escape sequences represent special characters such as a newline or a literal backslash. Quote style does not change the text's type. A name holding text refers to a string object, not a collection whose characters can be replaced by assignment.

Immutability means s[0] = 'N' is not permitted. To correct a name, build a new string and rebind the variable. Methods such as upper and replace also return new strings. If s refers to the original and t receives a changed version, s remains unchanged unless explicitly rebound. This differs from list methods that may modify a shared object. Distinguish object mutation from reassigning the name used to refer to an object.

2. Length, indexing and valid boundaries

len(s) counts the string's elements. Positive indices begin at zero and end at len(s) − 1. Negative indices count backward: −1 is the last element and −len(s) is the first. Access beyond these positions raises IndexError.

For s = 'LIBRARY', the positive indices run from L at zero to Y at six. The character R occurs twice, so specify an index or matching rule rather than referring to “the position of R” ambiguously. The empty string has length zero and no valid character index. Spaces and punctuation count as elements too. Unicode combining marks can complicate the relation between visible symbols and code points, so avoid assuming that every visibly displayed symbol is necessarily exactly one indexed element.

3. Slicing with start, stop and step

A slice s[start:stop:step] selects a sequence of positions. The stop is excluded. A positive step moves right; a negative step moves left. Omitting bounds uses defaults appropriate to the direction. Unlike indexing, out-of-range slice bounds are normally clipped, while a zero step is invalid.

s = "LIBRARY"
print(s[1:6:2])
print(s[-3:])
print(s[::-1])
print(s[50:])

Output:

IRR
ARY
YRARBIL

The first slice selects indices one, three and five: I, R and R. The last print displays an empty line because the slice is empty. Reversal with a negative step relies on omitted defaults; replacing those defaults casually with explicit values can change the result. Always list selected indices before writing characters in an output-prediction answer.

4. Operators, comparison and membership

The + operator concatenates strings and * repeats them by an integer count. Repetition by zero yields an empty string. Use in and not in for substring membership, not merely single-character checks. Comparisons are lexicographic: the first differing Unicode code point determines the order, and a matching shorter prefix sorts before its longer extension.

For example, 'Lab' and 'lab' do not compare equal because comparison is case-sensitive. If a task explicitly ignores case, normalise both operands consistently before comparing. Do not claim alphabetical order always matches Unicode ordering across scripts or punctuation. A numeric-looking string remains text, so sorting such identifiers can differ from sorting their integer values. Choose conversion only if the task treats them as quantities rather than codes with meaningful formatting.

5. Searching and counting methods

find(sub) returns the first matching index or −1 if absent. index(sub) also finds a position but raises ValueError if absent. count(sub) counts non-overlapping occurrences. startswith and endswith test boundaries and return Boolean values. Check the returned information instead of assuming every method returns a string.

word = "coconut"
print(word.find("co"), word.find("z"))
print(word.count("co"), word.startswith("co"))
print("aaaa".count("aa"))

Output:

0 -1
2 True
2

The substring co begins at zero and occurs again at two. There is no z. The final count is two because the matching pairs do not overlap. A find result of zero is a successful match, so a test such as if word.find(...) can misclassify a match at the beginning; compare against −1 explicitly.

6. Changing appearance and testing character classes

Methods upper, lower, capitalize, title and swapcase return transformed text. isalpha, isdigit, isalnum and isspace test character properties. These methods generally require at least one character and all relevant characters to satisfy the property; a space inside a word makes isalpha false.

A school account name containing letters and digits can pass isalnum, while one containing an underscore does not. A digit test is not a complete validation rule for every numeric format: a decimal point and a minus sign are not digit characters. Therefore a negative decimal string cannot be accepted by isdigit alone. State the accepted format before designing validation. Case conversion helps matching but does not justify altering the way a person's name must appear in a final document.

7. Cleaning, splitting and joining

strip removes specified characters from both ends, defaulting to whitespace. It does not remove every interior space. lstrip and rstrip limit the affected side. replace(old, new) produces a new string with substitutions. split creates a list of fields, and a separator string's join method combines strings from an iterable.

record = "  Pune,Jaipur,Kochi  "
parts = record.strip().split(",")
print(parts)
print(" / ".join(parts))
print(record.strip().replace(",", ";"))

Output:

['Pune', 'Jaipur', 'Kochi']
Pune / Jaipur / Kochi
Pune;Jaipur;Kochi

The order of operations matters. Trimming the outside before splitting removes padding from the record but does not automatically clean arbitrary padding around every field. split() without a separator treats runs of whitespace differently from split(' '), so choose deliberately when input may contain repeated spaces.

8. Traversal and a worked text algorithm

A traversal examines elements in order, either directly or by index. Direct traversal is convenient for counting; indices help when neighbouring positions or locations matter. For a vowel count, normalise case and compare each character with a defined set of vowel letters.

text = "Study in Udaipur"
vowels = 0
for ch in text.lower():
    if ch in "aeiou":
        vowels += 1
print(vowels)
clean = "level"
print(clean == clean[::-1])

Output:

6
True

The vowel rule counts ordinary English vowel letters, not every linguistic vowel sound. The palindrome test compares the complete original with its reversal. For a phrase palindrome, first define whether to ignore case, punctuation and spaces; different normalisation policies answer different questions. Preserve the original text if it must later be displayed, and store cleaned text separately. These explicit assumptions turn an apparently simple algorithm into a dependable solution.

A reliable approach to questions

  1. Read the command word before choosing an answer. A definition needs the distinguishing feature; a comparison needs matching criteria on both sides; an application needs a reason linked to the situation.

  2. Extract the supplied evidence and assumptions. Keep a small working table rather than relying on memory. If information is absent, state the limit instead of inventing a value or claiming certainty.

  3. Work through the relevant rule one step at a time. For a program, record the changing state; for a scenario, connect the requirement to the feature that meets it. Explain why the closest alternative fails.

  4. Check the result against the original question, including boundary cases, units and wording. Present a concise final answer followed by enough reasoning for another student to reproduce your conclusion.

Connections that matter

  • Number encoding explains how Unicode text becomes stored bytes.

  • Loops implement traversal and text statistics.

  • Lists receive split results and supply strings to join.

Common mistakes

  • Treating find result zero as failure: zero is a valid match position.

  • Expecting strip to remove interior spaces: it affects the ends.

  • Including a slice stop position: stop is excluded.

  • Expecting upper to mutate the original: assign the returned string when needed.

Revision checklist

  • I can explain string creation, immutability and rebinding.

  • I can trace indexing, slicing and negative steps.

  • I can use searching and character-test methods correctly.

  • I can clean, split and join text with explicit assumptions.

  • I can design vowel-count and palindrome algorithms.

Practise this topic →

Discussion

Sign in to join the discussion.

Sign in

No comments yet. Be the first to share your thoughts.