Unit 2: Computational Thinking & Programming
Chapter 5: Strings in Python
1. Introduction to Strings
A String is an ordered, immutable sequence of Unicode characters enclosed in quotation marks.
- Single Quotes: 'Hello World'
- Double Quotes: "Computer Science"
- Triple Quotes: """Multi-line string""" or \'\'\'Multi-line text\'\'\'
Immutability of Strings
Strings are strictly immutable. Once created in memory, individual characters of a string cannot be modified or replaced in-place:
s = "Python"
s[0] = "J" # TypeError: 'str' object does not support item assignment
To "change" a string, a new string object must be constructed and assigned back to the variable.
2. String Indexing and Traversing
Dual Indexing System
Python provides both forward (positive) and backward (negative) indexing:
Positive Index: 0 1 2 3 4 5
Character: | P | y | t | h | o | n |
Negative Index: -6 -5 -4 -3 -2 -1
- Forward indexing runs from
0tolen(s) - 1. - Backward indexing runs from
-1(last character) to-len(s)(first character).
msg = "Python"
print(msg[0]) # 'P'
print(msg[-1]) # 'n'
3. String Slicing: s[start:stop:step]
Slicing extracts a substring without modifying the original string:
- start: Index where slice begins (inclusive, defaults to 0).
- stop: Index where slice terminates (exclusive, defaults to string length).
- step: Index stride/increment (defaults to 1; can be negative).
text = "ComputerScience"
# Basic slices
print(text[0:8]) # 'Computer' (indices 0 through 7)
print(text[8:]) # 'Science' (index 8 to end)
print(text[:8]) # 'Computer' (beginning up to index 7)
print(text[::2]) # 'Cmuercec' (every 2nd character)
# Slicing with negative step
print(text[::-1]) # 'ecneicSretupmoC' (Reversed string!)
print(text[7:0:-1]) # 'retupmo'
4. String Operators
- Concatenation (
+): Joins two strings together."Data" + "Base"$\to$"DataBase" - Replication (
*): Repeats a string by an integer factor."Go!" * 3$\to$"Go!Go!Go!" - Membership (
in,not in): Checks substring existence.'put' in "Computer"$\to$True - Comparison (
==,!=,<,>,<=,>=): Compares character-by-character using Unicode/ASCII ordinals."Apple" < "Banana"$\to$True(ord('A')=65 < ord('B')=66)
5. Built-in String Functions and Methods
| Method | Description | Example | Result |
|---|---|---|---|
len(s) |
Returns total number of characters. | len("CBSE") |
4 |
s.capitalize() |
First character uppercase, rest lowercase. | "delhi".capitalize() |
"Delhi" |
s.title() |
Capitalizes first letter of every word. | "computer science".title() |
"Computer Science" |
s.upper() |
Converts all characters to uppercase. | "python".upper() |
"PYTHON" |
s.lower() |
Converts all characters to lowercase. | "PYTHON".lower() |
"python" |
s.count(sub) |
Counts non-overlapping occurrences. | "banana".count("an") |
2 |
s.find(sub) |
Returns lowest index of sub; -1 if not found. |
"Python".find("th") |
2 |
s.index(sub) |
Like find(), but raises ValueError if absent. |
"Python".index("th") |
2 |
s.replace(old, new) |
Returns a copy with all occurrences replaced. | "Hello".replace("l", "r") |
"Herro" |
s.split(sep) |
Splits string into a list of strings. | "apple,banana".split(",") |
['apple', 'banana'] |
sep.join(iterable) |
Joins elements of iterable with separator. | "-".join(["A", "B", "C"]) |
"A-B-C" |
s.strip() |
Removes leading and trailing whitespace. | " hi ".strip() |
"hi" |
s.isdigit() |
True if all characters are digits. |
"2024".isdigit() |
True |
s.isalpha() |
True if all characters are alphabetic. |
"Code802".isalpha() |
False |
s.isalnum() |
True if all characters are alphanumeric. |
"Code802".isalnum() |
True |
6. Board Exam Practice Questions & Solutions
Q1. What will be the output of the following code snippet?
s = "Class XI Computer Science"
print(s[9:17])
print(s[-7:])
print(s[::3])
Answer:
Computer
Science
CsICmrrnc
Q2. Write a Python function to test whether a given string is a Palindrome (reads same forwards and backwards). Answer:
def is_palindrome(text):
# Remove spaces and convert to lowercase for uniform check
cleaned = text.replace(" ", "").lower()
return cleaned == cleaned[::-1]
print(is_palindrome("madam")) # True
print(is_palindrome("racecar")) # True
print(is_palindrome("python")) # False
Q3. Write a program to count total vowels, consonants, digits, and spaces in a given string. Answer:
text = input("Enter a string: ")
vowels = consonants = digits = spaces = 0
for ch in text:
if ch.lower() in "aeiou":
vowels += 1
elif ch.isalpha():
consonants += 1
elif ch.isdigit():
digits += 1
elif ch.isspace():
spaces += 1
print(f"Vowels: {vowels}, Consonants: {consonants}, Digits: {digits}, Spaces: {spaces}")