String Manipulation in Python Class-XI
๐งฉ 1. Introduction to Strings
- Definition:
A string in Python is a sequence of characters enclosed within single quotes (' '), double quotes (" "), or triple quotes (''' '''or""" """). - Examples:
name = 'Alakshya' city = "Dehradun" paragraph = '''This is a multi-line string.''' - Strings are Immutable:
Once created, a string cannot be changed. Any modification creates a new string.
โ๏ธ 2. String Slicing
- Definition:
Slicing means extracting a portion (substring) of a string using index positions. - Syntax:
string[start : end : step]startโ index to begin (default = 0)endโ index to stop (excluded)stepโ increment (default = 1)
- Examples:
s = “PYTHON”
print(s[0:3]) # Output: PYT
print(s[2:]) # Output: THON
print(s[:4]) # Output: PYTH
print(s[::2]) # Output: PTO
print(s[::-1]) # Output: NOHTYP (reversed string)
๐ข 3. String Operations
A. Concatenation (+)
Combines or joins two or more strings.
a = "Hello"
b = "World"
print(a + " " + b) # Output: Hello World
B. Repetition (*)
Repeats the string multiple times.
print("Hi! " * 3) # Output: Hi! Hi! Hi!
C. Membership Operators (in, not in)
Check whether a substring exists in another string.
s = "computer"
print("put" in s) # True
print("Comp" not in s) # True
๐ 4. Traversing a String Using Loops
You can use loops to access each character in a string.
Using for loop:
word = "HELLO"
for ch in word:
print(ch)
Using while loop:
word = "HELLO"
i = 0
while i < len(word):
print(word[i])
i += 1
๐งฎ 5. Built-in String Functions and Methods
Here are some commonly used string methods in Python:
| Function / Method | Description | Example |
|---|---|---|
len(s) | Returns length of string | len("India") โ 5 |
capitalize() | Converts first character to uppercase | "hello".capitalize() โ "Hello" |
title() | Converts first letter of each word to uppercase | "welcome to school".title() โ "Welcome To School" |
lower() | Converts all characters to lowercase | "HELLO".lower() โ "hello" |
upper() | Converts all characters to uppercase | "hello".upper() โ "HELLO" |
count(sub) | Returns number of occurrences of substring | "banana".count("a") โ 3 |
find(sub) | Returns index of first occurrence; -1 if not found | "python".find("t") โ 2 |
index(sub) | Like find(), but gives error if not found | "python".index("y") โ 1 |
endswith(sub) | Checks if string ends with substring | "hello".endswith("lo") โ True |
startswith(sub) | Checks if string starts with substring | "hello".startswith("he") โ True |
isalnum() | True if all characters are letters or digits | "abc123".isalnum() โ True |
isalpha() | True if all characters are alphabets | "abc".isalpha() โ True |
isdigit() | True if all characters are digits | "123".isdigit() โ True |
islower() | True if all characters are lowercase | "hello".islower() โ True |
isupper() | True if all characters are uppercase | "HELLO".isupper() โ True |
isspace() | True if string contains only whitespace | " ".isspace() โ True |
lstrip() | Removes spaces from left | " hello".lstrip() โ "hello" |
rstrip() | Removes spaces from right | "hello ".rstrip() โ "hello" |
strip() | Removes spaces from both sides | " hello ".strip() โ "hello" |
replace(old,new) | Replaces substring with another | "good morning".replace("morning","evening") โ "good evening" |
join(iterable) | Joins elements using string as separator | " ".join(["Python","is","fun"]) โ "Python is fun" |
partition(sep) | Splits into 3 parts: before, separator, after | "hello@world".partition("@") โ ('hello', '@', 'world') |
split(sep) | Splits string into list using separator | "a,b,c".split(",") โ ['a','b','c'] |
๐ง 6. Summary
- Strings are immutable sequences of characters.
- They can be indexed, sliced, and traversed.
- Operations include concatenation, repetition, and membership testing.
- Python provides a rich set of built-in methods for string manipulation.
๐งฉ 7. Sample Questions for Practice
- Write a Python statement to extract โthonโ from
"python". - What will be the output of
"HELLO".lower()? - Write a Python expression to check if
"data"exists in"database". - What is the output of
"apple".replace('p','b')? - Write a program to count vowels in a given string.
MCQs โ Strings in Python
1. What is a string in Python?
A. A numeric data type
B. A sequence of characters
C. A Boolean value
D. A list of integers
2. What is the output of:
print("hello" + "world")
A. helloworld
B. hello world
C. hello+world
D. Error
3. Which operator is used for repetition of strings?
A. +
B. *
C. **
D. %
4. What is the output of:
print("hi" * 3)
A. hihihi
B. hi3
C. 3hi
D. Error
5. Membership operator in is used to:
A. Compare lengths
B. Add strings
C. Check substring presence
D. Split a string
6. What will be the output of:
s = "computer"
print(s[2:6])
A. comp
B. mput
C. pute
D. com
7. What is the result of:
s = "python"
print(s[-3:])
A. tho
B. hon
C. ton
D. Error
8. Which function returns the length of a string?
A. length()
B. size()
C. len()
D. strlen()
9. What is the output of:
print("hello".upper())
A. HELLO
B. Hello
C. hello
D. error
10. What is the output of:
print("HELLO".lower())
A. hello
B. HELLO
C. Hello
D. error
11. The function capitalize() converts:
A. All characters to lowercase
B. All characters to uppercase
C. First character to uppercase
D. Last character to uppercase
12. Output of:
print("india is great".title())
A. India Is Great
B. India is great
C. INDIA IS GREAT
D. india is great
13. Which method counts occurrences of a substring?
A. total()
B. count()
C. find()
D. index()
14. Output of:
print("banana".count("a"))
A. 1
B. 2
C. 3
D. 4
15. Which method returns the index of first occurrence of a substring (or -1)?
A. index()
B. find()
C. search()
D. first()
16. Which method raises an error if substring not found?
A. find()
B. index()
C. count()
D. locate()
17. Output of:
print("hello".startswith("he"))
A. True
B. False
C. None
D. Error
18. Output of:
print("world".endswith("ld"))
A. True
B. False
C. ld
D. Error
19. What does isdigit() check?
A. All characters are letters
B. All characters are digits
C. Only first character is digit
D. Only last character is digit
20. Output of:
print("abc123".isalnum())
A. True
B. False
C. abc
D. Error
21. Output of:
print("python".isupper())
A. True
B. False
C. python
D. PYTHON
22. Which method checks if all characters are alphabets?
A. isdigit()
B. isalpha()
C. isalnum()
D. alpha()
23. Output of:
print(" hello".lstrip())
A. hello
B. hello
C. “hello “
D. “hello” with no right spaces
24. Output of:
print("hello ".rstrip())
A. hello
B. hello___
C. hello
D. hello with leading spaces
25. Output of:
print(" hi ".strip())
A. hi
B. hi
C. ” hi “
D. Error
26. Which method replaces part of a string with another?
A. change()
B. replace()
C. swap()
D. update()
27. Output of:
print("hello world".replace("world", "python"))
A. hello world
B. hello python
C. python hello
D. Error
28. Output of:
print(",".join(["a", "b", "c"]))
A. abc
B. a,b,c
C. a b c
D. a; b; c
29. The method split() returns:
A. A tuple
B. A string
C. A list
D. A dictionary
30. Output of:
print("welcome-to-python".partition("-"))
A. (‘welcome’, ‘-‘, ‘to-python’)
B. [‘welcome’, ‘to’, ‘python’]
C. (‘welcome-to-python’, ‘-‘, ”)
D. Error
โ ANSWER KEY
1-B
2-A
3-B
4-A
5-C
6-B
7-B
8-C
9-A
10-A
11-C
12-A
13-B
14-C
15-B
16-B
17-A
18-A
19-B
20-A
21-B
22-B
23-A
24-A
25-A
26-B
27-B
28-B
29-C
30-A