How to Use This Page
1. Attempt every exercise on your own before reading the solution. 2. Compare your approach with the solution — focus on the logic, not just the final answer. 3. Type and run the Python code on your computer; reading alone is not enough. 4. Review the Common Mistakes section to avoid errors that cost marks in exams.
Key Concepts
| Concept | Syntax / Example | Description |
|---|---|---|
| String creation | s = "Hello" | Strings use single, double, or triple quotes |
| Indexing | s[0] → 'H' | Access a character by position (0-based) |
| Negative indexing | s[-1] → 'o' | Count from the end (-1 is last) |
| Slicing | s[1:4] → 'ell' | Extract substring: start inclusive, stop exclusive |
| Step slicing | s[::2] → 'Hlo' | Every 2nd character |
| Reverse | s[::-1] → 'olleH' | Reverses the string |
| Immutability | Cannot do s[0]='h' | Strings cannot be changed in place |
| Escape characters | \n, \t, \\, \" | Special characters inside strings |
| String formatting | f-strings, .format(), % | Insert values into strings |
Important String Methods
| Method | Example | Result |
|---|---|---|
upper() | "hi".upper() | "HI" |
lower() | "HI".lower() | "hi" |
title() | "hello world".title() | "Hello World" |
strip() | " hi ".strip() | "hi" |
lstrip() | " hi ".lstrip() | "hi " |
rstrip() | " hi ".rstrip() | " hi" |
find() | "hello".find("ll") | 2 |
rfind() | "hello".rfind("l") | 3 |
index() | "hello".index("ll") | 2 |
replace() | "hi".replace("h", "H") | "Hi" |
split() | "a b c".split() | ["a", "b", "c"] |
join() | "-".join(["a","b"]) | "a-b" |
count() | "banana".count("an") | 2 |
startswith() | "hello".startswith("he") | True |
endswith() | "hello".endswith("lo") | True |
isalpha() | "abc".isalpha() | True |
isdigit() | "123".isdigit() | True |
isalnum() | "abc123".isalnum() | True |
isspace() | " ".isspace() | True |
swapcase() | "HeLLo".swapcase() | "hEllO" |
capitalize() | "hello world".capitalize() | "Hello world" |
center() | "hi".center(10, "-") | "----hi----" |
zfill() | "5".zfill(3) | "005" |
Multiple Choice Questions (MCQs)
Q1. What is the output of "Hello"[1:4]?
- (a) "Hel"
- (b) "ell"
- (c) "ello"
- (d) "ell"
Q2. Which method converts "hello world" to "Hello World"?
- (a)
upper() - (b)
capitalize() - (c)
title() - (d)
swapcase()
Q3. What does "banana".count("an") return?
- (a) 1
- (b) 2
- (c) 3
- (d) 0
Q4. Strings in Python are:
- (a) Mutable
- (b) Immutable
- (c) Both mutable and immutable
- (d) None of the above
Q5. What is the result of "Python"[-3:]?
- (a) "tho"
- (b) "hon"
- (c) "Pyt"
- (d) Error
Fill in the Blanks
Q1. The ______ method removes leading and trailing whitespace from a string.
Q2. ______ is the escape character for a new line.
Q3. "hello".find("x") returns ______.
Q4. The ______ method joins elements of a list into a single string using a separator.
Q5. "5".zfill(4) returns ______.
True or False
Q1. Strings in Python can be modified using indexing, e.g., s[0] = 'h'.
Q2. "Hello".lower() changes the original string.
Q3. The split() method returns a list.
Q4. Triple quotes can be used to create multi-line strings.
Q5. "123".isdigit() returns True.
Match the Following
| Column A | Column B |
|---|---|
| 1. `"abc".upper() | (a) "ABC123" (True) |
| 2. `"abc123".isalnum() | (b) "AB" |
| 3. `"a-b-c".split("-") | (c) ["a", "b", "c"] |
| 4. `"Hello"[1:3] | (d) "ABCD" |
| 5. `"ab".join(["1","2","3"]) | (e) "1ab2ab3" |
| Column A | Column B |
|---|---|
1. "abc".upper() | (a) "ABC" |
2. "abc123".isalnum() | (b) True |
3. "a-b-c".split("-") | (c) ["a", "b", "c"] |
4. "Hello"[1:3] | (d) "el" |
5. "ab".join(["1","2","3"]) | (e) "1ab2ab3" |
Short Answer Questions
Q1. Explain string immutability with an example.
Strings in Python cannot be modified after creation. Any operation that seems to modify a string actually creates a new string.
s = "Hello"
# s[0] = "h" # TypeError: 'str' object does not support item assignment
# To "change" a string, create a new one:
s = "h" + s[1:] # Create new string "hello"
print(s) # hello
The original "Hello" object remains in memory until garbage-collected.
Q2. What is string slicing? Explain with examples.
Slicing extracts a substring using the syntax s[start:stop:step].
s = "Python"
print(s[0:3]) # Pyt (indices 0,1,2)
print(s[2:]) # thon (from index 2 to end)
print(s[:4]) # Pyth (from start to index 3)
print(s[-3:]) # hon (last 3 characters)
print(s[::2]) # Pto (every 2nd character)
print(s[::-1]) # nohtyP (reversed)
Q3. Differentiate between find() and index().
| Feature | find() | index() |
|---|---|---|
| Returns position if found | Yes | Yes |
| Returns if not found | -1 | Raises ValueError |
| Usage | Safe searching | When substring is guaranteed |
s = "Hello World"
print(s.find("World")) # 6
print(s.index("World")) # 6
print(s.find("xyz")) # -1
# s.index("xyz") # ValueError: substring not found
Q4. Explain string formatting methods in Python.
Python offers three ways to format strings:
name = "Arun"
marks = 95
# 1. f-string (Python 3.6+, recommended)
print(f"{name} scored {marks}") # Arun scored 95
# 2. format() method
print("{} scored {}".format(name, marks)) # Arun scored 95
print("{0} scored {1}".format(name, marks)) # Arun scored 95
print("{n} scored {m}".format(n=name, m=marks)) # Arun scored 95
# 3. %-formatting (older style)
print("%s scored %d" % (name, marks)) # Arun scored 95
Q5. List the escape characters in Python.
| Escape | Meaning |
|---|---|
\n | New line |
\t | Horizontal tab |
\\ | Backslash |
\' | Single quote |
\" | Double quote |
\r | Carriage return |
\b | Backspace |
print("Line1\nLine2") # Prints on two lines
print("A\tB\tC") # Prints with tabs
print("She said \"Hi\"") # Prints: She said "Hi"
Detailed Answers
Q1. Write a Python program to check whether a string is a palindrome.
def is_palindrome(s):
"""Check if a string is a palindrome."""
s = s.lower().replace(" ", "") # normalize
return s == s[::-1]
# Method 1: Using slicing
word = input("Enter a string: ")
if is_palindrome(word):
print(word, "is a palindrome")
else:
print(word, "is not a palindrome")
# Method 2: Using loop (manual comparison)
def is_palindrome_loop(s):
s = s.lower().replace(" ", "")
left, right = 0, len(s) - 1
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return True
Test: "madam" → True, "hello" → False, "racecar" → True
Q2. Write a program to count the number of vowels, consonants, digits, and special characters in a string.
def count_chars(s):
"""Count vowels, consonants, digits, and special characters."""
vowels = "aeiouAEIOU"
v = c = d = sp = 0
for char in s:
if char.isalpha():
if char in vowels:
v += 1
else:
c += 1
elif char.isdigit():
d += 1
elif char != " ":
sp += 1
return v, c, d, sp
s = input("Enter a string: ")
v, c, d, sp = count_chars(s)
print(f"Vowels: {v}")
print(f"Consonants: {c}")
print(f"Digits: {d}")
print(f"Special characters: {sp}")
Q3. Write a program to reverse each word in a sentence while keeping word order.
sentence = input("Enter a sentence: ")
words = sentence.split()
reversed_words = [word[::-1] for word in words]
result = " ".join(reversed_words)
print("Original:", sentence)
print("Reversed words:", result)
# Input: Hello World Python
# Output: olleH dlroW nohtyP
Q4. Write a program to remove all duplicate characters from a string while preserving order.
def remove_duplicates(s):
"""Remove duplicate characters, preserving first occurrence order."""
seen = set()
result = ""
for char in s:
if char not in seen:
seen.add(char)
result += char
return result
s = input("Enter a string: ")
print("After removing duplicates:", remove_duplicates(s))
# Input: "programming" → Output: "progamin"
Q5. Write a program to check if two strings are anagrams of each other.
def are_anagrams(s1, s2):
"""Check if two strings are anagrams."""
s1 = s1.lower().replace(" ", "")
s2 = s2.lower().replace(" ", "")
return sorted(s1) == sorted(s2)
str1 = input("Enter first string: ")
str2 = input("Enter second string: ")
if are_anagrams(str1, str2):
print("The strings are anagrams")
else:
print("The strings are not anagrams")
# Input: "listen", "silent" → Anagrams
# Input: "hello", "world" → Not anagrams
Q6. Write a program to find the most frequent character in a string.
def most_frequent(s):
"""Find the most frequent character in a string."""
freq = {}
for char in s:
if char != " ":
freq[char] = freq.get(char, 0) + 1
max_char = max(freq, key=freq.get)
return max_char, freq[max_char]
s = input("Enter a string: ")
char, count = most_frequent(s)
print(f"Most frequent character: '{char}' appears {count} times")
# Input: "programming" → 'g' and 'r' and 'm' each appear twice
# The max() returns the first one encountered
Q7. Write a program to convert between different string cases.
s = "hello World PYTHON"
print("Original: ", s)
print("upper(): ", s.upper()) # HELLO WORLD PYTHON
print("lower(): ", s.lower()) # hello world python
print("title(): ", s.title()) # Hello World Python
print("capitalize(): ", s.capitalize()) # Hello world python
print("swapcase(): ", s.swapcase()) # HELLO wORLD python
Common Mistakes
| Mistake | Why It's Wrong | Correction |
|---|---|---|
s[0] = 'h' | Strings are immutable — TypeError | Use s = 'h' + s[1:] to create a new string |
s.find() returns 0 when found at start | Confusing 0 (found at index 0) with False | Remember: find() returns the index or -1 |
| Off-by-one in slicing | s[1:4] gives indices 1,2,3 (not 4) | Stop index is exclusive |
split() vs join() confusion | split() breaks string → list; join() joins list → string | sep.join(list) and str.split(sep) |
Forgetting replace() doesn't modify in place | s.replace('a','b') returns a new string | Assign: s = s.replace('a','b') |
Using == to compare case-insensitively | "Hello" == "hello" is False | Use .lower() or .casefold() before comparing |
Exam Checklist
- [ ] I can use indexing and slicing on strings (positive and negative indices)
- [ ] I can explain string immutability and work around it
- [ ] I know all key string methods: upper, lower, find, replace, split, join, strip, count, isalpha, isdigit, isalnum
- [ ] I can format strings using f-strings, .format(), and %-formatting
- [ ] I understand escape characters (\n, \t, \\, \', \")
- [ ] I can write programs for palindrome check, character counting, word reversal
- [ ] I can differentiate find() vs index(), split() vs join()
- [ ] I can trace string operations and predict outputs correctly
