Revision Notes on Strings for Python (Class 12 CS)

  Revision Notes on Strings for Python (Class 12 CS). Strings are a high-weightage topic, appearing frequently in "Predict the Output" and coding questions.


1. The Basics

  • Definition: A sequence of characters enclosed in quotes (' ', " ", or """ """).

  • Immutability: Strings are Immutable. You cannot change individual characters in place.

    Python
    s = "Hello"
    s[0] = "M"  # ❌ TypeError!
    s = "M" + s[1:] # ✅ Correct (Creates a NEW string)
    

2. Indexing & Traversal

Each character has a unique position (index).

  • Forward Indexing: Starts from 0 (Left to Right).

  • Backward Indexing: Starts from -1 (Right to Left).

  • Traversal: Iterating through a string.

    Python
    # Method 1: By Element
    for ch in "Code":
        print(ch) 
    
    # Method 2: By Index
    S = "Code"
    for i in range(len(S)):
        print(S[i])
    

3. String Slicing (The Most Important Part)

Syntax: String[Start : Stop : Step]

  • Start: Inclusive (default 0).

  • Stop: Exclusive (default Length).

  • Step: Jump value (default 1).

Cheat Sheet Examples: | Code | Output | Logic | | :--- | :--- | :--- | | S = "COMPUTER" | | | | S[1:5] | "OMPU" | Index 1 to 4. | | S[:3] | "COM" | Start to Index 2. | | S[4:] | "UTER" | Index 4 to End. | | S[::2] | "CMUE" | Every 2nd character. | | S[::-1] | "RETUPMOC" | Reverses the string. | | S[-4:] | "UTER" | Last 4 characters. |


4. String Operators

  1. Concatenation (+): Joins strings.

    • "Hi" + "Bye" "HiBye"

    • Note: Cannot add Number to String ("Hi" + 5 Error).

  2. Repetition (*): Repeats string.

    • "No" * 3 "NoNoNo"

  3. Membership (in, not in): Checks presence.

    • "a" in "Apple" False (Case sensitive).


5. Must-Know String Methods

These are crucial for "Output" questions.

A. Case Conversion

  • s.upper(): Returns uppercase.

  • s.lower(): Returns lowercase.

  • s.capitalize(): First char capital, rest lower.

  • s.title(): First char of every word capital.

  • s.swapcase(): Swaps case (lower upper).

B. Validation (Returns True/False)

  • s.isalpha(): True if all chars are alphabets (No digits/spaces).

  • s.isdigit(): True if all chars are numbers.

  • s.isalnum(): True if alphabets OR numbers (No symbols/spaces).

  • s.islower() / s.isupper(): Checks case.

  • s.isspace(): True if string contains only whitespace.

C. Searching & Editing

  • s.count(sub): Counts occurrences of substring.

    • "banana".count("a") 3

  • s.find(sub): Returns index of first occurrence. Returns -1 if not found.

  • s.index(sub): Same as find, but returns Error if not found.

  • s.replace(old, new): Replaces all occurrences.

    • "Beep".replace("e", "o") "Boop"

D. Splitting & Joining (Very Important)

  1. split(sep): Converts String List.

    Python
    s = "Python is fun"
    L = s.split() 
    # Result: ['Python', 'is', 'fun']
    
  2. join(iterable): Converts List String.

    Python
    L = ['Python', 'is', 'fun']
    s = "-".join(L)
    # Result: "Python-is-fun"
    

E. Cleaning

  • s.strip(): Removes leading and trailing whitespace.

  • s.lstrip(): Removes left whitespace.

  • s.rstrip(): Removes right whitespace.


6. Common Exam Errors to Avoid

  1. Difference between find() and index():

    • Question: "What happens if the substring is not found?"

    • find() returns -1 (Safe). index() crashes (Error).

  2. Strings are Immutable:

    • You cannot write s.upper(). You must write s = s.upper() to save the change.

  3. Split Logic:

    • "A,,B".split(",") produces ['A', '', 'B']. (Empty string between commas).

Quick Test

Predict the output:

Python
txt = "Exam 2025"
print(txt.replace("20", "!!").upper().split())

(Answer: ['EXAM', '!!25'])

Comments

Popular Posts