Computer Science: Class 11 — Chapter 8: Strings

Introduction to Strings

A string is a sequence of one or more UNICODE characters. In Python, strings are sequence data types, similar to lists and tuples, where each item is indexed by an integer.

String Creation and Representation

Strings can be created by enclosing characters in single, double, or triple quotes. Triple quotes ( """ or ''' ) allow strings to span multiple lines.

  
    >>> str1 = 'Hello World!'
    >>> str2 = "Hello World!"
    >>> str3 = """Hello World!
    welcome to the world of Python"""
  
Accessing Characters via Indexing

Each character in a string is accessed using indexing via square brackets [] . Python supports both positive (left-to-right) and negative (right-to-left) indexing.

The index of the first character is 0 (or -n ), and the last character is n-1 (or -1 ), where n is the length of the string.

Positive Indices 0 1 2 3 4 5 6 7 8 9 10 11
String H e l l o W o r l d !
Negative Indices -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

Technical Profile: Indexing Errors

  • Architecture Layer / Tier: Python Runtime Environment
  • Operational Mechanics & Syntax: Accessing an index outside the range [-n, n-1] raises an IndexError . Using a non-integer index (e.g., float) raises a TypeError .
  • System Trade-offs & Failures: Strict type checking prevents silent memory corruption but requires explicit exception handling or bounds checking.
String Immutability

Strings in Python are immutable . Once created, their elements cannot be changed or replaced in-place. Attempting to do so raises a TypeError .

  
    >>> str1 = "Hello World!"
    >>> str1[1] = 'a'
    TypeError: 'str' object does not support item assignment
  
String Operations
Concatenation and Repetition
  • Concatenation ( + ): Joins two strings together to form a new string.
  • Repetition ( * ): Repeats a string a specified number of \times.
  
    >>> 'Hello' + 'World!'
    'HelloWorld!'
    >>> 'Hello' * 2
    'HelloHello'
  
Membership Operators

Python provides two membership operators: in and not in . They check if a substring exists within a string, returning a boolean value.

  
    >>> 'W' in 'Hello World!'
    True
    >>> 'My' not in 'Hello World!'
    True
  
Slicing and Step Sizes

Slicing allows retrieving a subset of a string using the syntax str1[n:m:k] , where n is the start index (inclusive), m is the stop index (exclusive), and k is the step size.

  • If n is omitted, slicing starts from index 0.
  • If m is omitted, slicing goes to the end of the string.
  • A negative step size (e.g., -1 ) reverses the string.
  
    >>> str1 = 'Hello World!'
    >>> str1[1:5]
    'ello'
    >>> str1[::-1]
    '!dlroW olleH'
  
Traversing a String

String traversal involves accessing each character of a string sequentially. This can be achieved using loops.

Traversal Methods

Method A: Using a for loop (Character-based)

  
    str1 = 'Hello World!'
    for ch in str1:
    print(ch, end='')
  

Method B: Using a while loop (Index-based)

  
    str1 = 'Hello World!'
    index = 0
    while index < len(str1):
    print(str1[index], end='')
    index += 1
  
Built-in Functions and Methods

Python provides a rich set of built-in methods for string manipulation. Below is a comprehensive matrix of these methods.

Method Description Example & Output
len() Returns the length of the string. len('Hello') → 5
title() Capitalizes the first letter of each word. 'hello WORLD'.title() → 'Hello World'
lower() Converts all characters to lowercase. 'Hello'.lower() → 'hello'
upper() Converts all characters to uppercase. 'Hello'.upper() → 'HELLO'
count(str, start, end) Counts occurrences of a substring. 'Hello Hello'.count('Hello') → 2
find(str, start, end) Returns the lowest index of substring, or -1 if not found. 'Hello'.find('l') → 2
index(str, start, end) Like find(), but raises ValueError if not found. 'Hello'.index('x') → ValueError
endswith(str) Returns True if string ends with specified suffix. 'Hello'.endswith('o') → True
startswith(str) Returns True if string starts with specified prefix. 'Hello'.startswith('H') → True
isalnum() Returns True if all characters are alphanumeric. 'Hello12'.isalnum() → True
islower() Returns True if all cased characters are lowercase. 'hello'.islower() → True
isupper() Returns True if all cased characters are uppercase. 'HELLO'.isupper() → True
isspace() Returns True if there are only whitespace characters. ' \n \t \r'.isspace() → True
istitle() Returns True if string is titlecased. 'Hello World'.istitle() → True
lstrip() Removes leading whitespace. ' Hello'.lstrip() → 'Hello'
rstrip() Removes trailing whitespace. 'Hello '.rstrip() → 'Hello'
strip() Removes leading and trailing whitespace. ' Hello '.strip() → 'Hello'
replace(old, new) Replaces occurrences of old substring with new. 'Hello'.replace('l', '*') → 'He**o'
join() Joins elements of an iterable with a separator. '-'.join('Hello') → 'H-e-l-l-o'
partition(sep) Splits string at first occurrence of separator into a 3-tuple. 'A-B-C'.partition('-') → ('A', '-', 'B-C')
split(sep) Splits string into a list of substrings based on separator. 'A B C'.split() → ['A', 'B', 'C']
Handling Strings: User-Defined Functions

This section explores custom programmatic solutions for common string manipulation tasks.

Program 8-1: Character Frequency Counter
Write a program with a user-defined function to count the number of \times a character (passed as argument) occurs in a given string.


Socio-Technical Analysis & Core Systemic Impact: This program demonstrates basic linear search traversal. By iterating through each character of the string and comparing it to the target character, it maintains a running counter. This is a fundamental pattern for frequency analysis in \text processing.

  
    def charCount(ch, st):
    count = 0
    for character in st:
    if character == ch:
    count += 1
    return count
  

Program 8-2: Vowel Obfuscation
Write a program with a user-defined function with string as a parameter which replaces all vowels in the string with '*'.


Socio-Technical Analysis & Core Systemic Impact: This program showcases string reconstruction. Since strings are immutable, we cannot modify the original string in-place. Instead, we build a new string character-by-character, substituting vowels with asterisks. This pattern is widely used in data masking and sanitization pipelines.

  
    def replaceVowel(st):
    newstr = ''
    for character in st:
    if character in 'aeiouAEIOU':
    newstr += '*'
    else:
    newstr += character
    return newstr
  

Program 8-5: Palindrome Verification
Write a program using a user-defined function to check if a string is a palindrome or not.


Socio-Technical Analysis & Core Systemic Impact: This algorithm uses a two-pointer approach (starting from both ends of the string and moving inward) to verify symmetry. It is highly efficient, running in $O(n)$ time complexity and requiring $O(1)$ auxiliary space, making it superior to reversing the entire string for large inputs.

  
    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
  
Exercises & Programming Problems

Test your understanding of string operations, slicing, and built-in methods with these exercises.

Conceptual Exercises
  1. Given mySubject = "Computer Science" , determine the output of:
    • print(mySubject[0:len(mySubject)]) → "Computer Science"
    • print(mySubject[-7:-1]) → "Scienc"
    • print(mySubject[::2]) → "Cmue ce"
    • print(mySubject[::-2]) → "encSrtpC"
  2. Given myAddress = "WZ-1,New Ganga Nagar,New Delhi" , determine the output of:
    • print(myAddress.split(',')) → ['WZ-1', 'New Ganga Nagar', 'New Delhi']
    • print(myAddress.replace('New','Old')) → "WZ-1,Old Ganga Nagar,Old Delhi"