Python String Methods | startswith(), endswith(), isalpha(), isdigit() & More | CBSE Class 11 Computer Science
Class 11 · Computer Science
Python String Methods (Part 2)
Python provides several built-in string methods for checking the properties of strings. These methods help programmers validate user input, compare text, and process strings efficiently.
Learning Objectives
- Use methods to check string properties.
- Validate user input.
- Understand Boolean return values.
- Apply string methods in real-life programs.
1. startswith() Method
The startswith() method checks whether a string begins with a specified character or substring. It returns True if the string starts with the given value; otherwise, it returns False.
Syntax
string.startswith(substring)
Example 1
text="Computer Science"
print(text.startswith("Computer"))
Output
True
Example 2
text="Computer Science"
print(text.startswith("Science"))
Output
False
Real-Life Applications
- Checking file extensions.
- Validating URLs.
- Checking prefixes in product codes.
- Filtering records.
2. endswith() Method
The endswith() method checks whether a string ends with a specified character or substring.
Syntax
string.endswith(substring)
Example 1
filename="notes.pdf"
print(filename.endswith(".pdf"))
Output
True
Example 2
filename="notes.pdf"
print(filename.endswith(".docx"))
Output
False
Real-Life Applications
- Checking image files.
- Validating document formats.
- Checking email domains.
- Filtering uploaded files.
3. isalnum() Method
The isalnum() method returns True if all characters in the string are alphabetic or numeric. Spaces and special characters are not allowed.
Syntax
string.isalnum()
Example 1
text="ABC123"
print(text.isalnum())
Output
True
Example 2
text="ABC 123"
print(text.isalnum())
Output
False
4. isalpha() Method
The isalpha() method returns True if all characters in the string are alphabetic.
Syntax
string.isalpha()
Example 1
name="Python"
print(name.isalpha())
Output
True
Example 2
name="Python3"
print(name.isalpha())
Output
False
Applications
- Name validation.
- Checking alphabet-only fields.
- Form validation.
5. isdigit() Method
The isdigit() method returns True if all characters in the string are digits.
Syntax
string.isdigit()
Example 1
roll="1256"
print(roll.isdigit())
Output
True
Example 2
roll="12A6"
print(roll.isdigit())
Output
False
Applications
- Mobile number validation.
- PIN verification.
- Checking numeric input.
6. islower() Method
The islower() method returns True if all alphabetic characters in the string are lowercase.
Syntax
string.islower()
Example
text="python"
print(text.islower())
Output
True
7. isupper() Method
The isupper() method returns True if all alphabetic characters are uppercase.
Syntax
string.isupper()
Example
text="PYTHON"
print(text.isupper())
Output
True
8. isspace() Method
The isspace() method returns True if the string contains only whitespace characters such as spaces or tabs.
Syntax
string.isspace()
Example 1
text=" "
print(text.isspace())
Output
True
Example 2
text=" Python "
print(text.isspace())
Output
False
Summary Table
| Method | Purpose | Return Type |
|---|---|---|
startswith() |
Checks starting text | Boolean |
endswith() |
Checks ending text | Boolean |
isalnum() |
Checks letters and digits | Boolean |
isalpha() |
Checks only alphabets | Boolean |
isdigit() |
Checks only digits | Boolean |
islower() |
Checks lowercase letters | Boolean |
isupper() |
Checks uppercase letters | Boolean |
isspace() |
Checks whitespace characters | Boolean |
Quick Revision
startswith()checks the beginning of a string.endswith()checks the ending of a string.isalnum()checks letters and digits only.isalpha()checks alphabets only.isdigit()checks digits only.islower()checks lowercase letters.isupper()checks uppercase letters.isspace()checks for whitespace characters.
Python String Methods (Part 3)
Python provides several powerful string methods for removing unwanted spaces, replacing text, joining strings, splitting strings, and dividing strings into parts. These methods are widely used in text processing, data cleaning, report generation, and file handling.
Learning Objectives
- Remove unwanted spaces from strings.
- Replace characters or words.
- Join multiple strings into one.
- Split strings into smaller parts.
- Partition strings using separators.
1. lstrip() Method
The lstrip() method removes all leading (left-side) whitespace characters from a string.
Syntax
string.lstrip()
Example
text=" Python"
print(text.lstrip())
Output
Python
2. rstrip() Method
The rstrip() method removes all trailing (right-side) whitespace characters from a string.
Syntax
string.rstrip()
Example
text="Python "
print(text.rstrip())
Output
Python
3. strip() Method
The strip() method removes whitespace characters from both the beginning and the end of a string.
Syntax
string.strip()
Example
text=" Python Programming "
print(text.strip())
Output
Python Programming
Difference between lstrip(), rstrip() and strip()
| Method | Removes Spaces From |
|---|---|
lstrip() |
Left side only |
rstrip() |
Right side only |
strip() |
Both sides |
4. replace() Method
The replace() method replaces all occurrences of a specified substring with another substring.
Syntax
string.replace(old,new)
Example 1
text="I like Java"
print(text.replace("Java","Python"))
Output
I like Python
Example 2
text="banana"
print(text.replace("a","@"))
Output
b@n@n@
Real-Life Applications
- Correcting spelling mistakes.
- Replacing old product names.
- Updating records.
- Formatting reports.
5. join() Method
The join() method joins the elements of a sequence using a specified separator.
Syntax
separator.join(sequence)
Example 1
words=["Python","is","Easy"]
print(" ".join(words))
Output
Python is Easy
Example 2
letters=["A","B","C","D"]
print("-".join(letters))
Output
A-B-C-D
6. partition() Method
The partition() method divides a string into three parts based on the first occurrence of a specified separator.
Syntax
string.partition(separator)
Example
text="Computer-Science"
print(text.partition("-"))
Output
('Computer', '-', 'Science')
Explanation: The output is a tuple containing the part before the separator, the separator itself, and the remaining part.
7. split() Method
The split() method divides a string into a list using the specified separator. If no separator is provided, it splits the string using whitespace.
Syntax
string.split(separator)
Example 1
text="Python Programming Language"
print(text.split())
Output
['Python', 'Programming', 'Language']
Example 2
text="A,B,C,D"
print(text.split(","))
Output
['A', 'B', 'C', 'D']
Difference between split() and partition()
| split() | partition() |
|---|---|
| Returns a list. | Returns a tuple. |
| Splits all occurrences. | Splits only at the first occurrence. |
| Separator is not included. | Separator is included in the result. |
Summary Table
| Method | Purpose |
|---|---|
lstrip() |
Removes left spaces. |
rstrip() |
Removes right spaces. |
strip() |
Removes spaces from both sides. |
replace() |
Replaces text. |
join() |
Joins sequence elements. |
partition() |
Splits into three parts. |
split() |
Splits into a list. |
Common Programming Mistakes
- Confusing
split()withpartition(). - Using
join()on non-string elements. - Expecting
strip()to remove spaces inside a string. - Assuming
replace()modifies the original string. - Forgetting that strings are immutable.
CBSE Important Programs
- Remove leading and trailing spaces.
- Replace a word in a sentence.
- Split a sentence into words.
- Join a list of names into a sentence.
- Count the total number of words.
- Extract the username from an email ID.
- Split a CSV record.
- Partition a filename using ".".
- Replace spaces with underscores.
- Clean user input before processing.
Viva Questions
- Differentiate between
strip(),lstrip(), andrstrip(). - What is the purpose of
replace()? - How does
join()work? - What is returned by
split()? - What is returned by
partition()? - Differentiate between
split()andpartition(). - Does
replace()modify the original string? - Why are strings called immutable?
- Give two applications of
split(). - Give two applications of
replace().
Exam Tips
- Remember that strings are immutable.
split()returns a list.partition()returns a tuple.join()joins sequence elements using a separator.replace()returns a new string.strip()removes spaces only from the beginning and end of a string.
Quick Revision
lstrip()removes leading spaces.rstrip()removes trailing spaces.strip()removes spaces from both ends.replace()replaces text.join()joins sequence elements.partition()returns a tuple of three elements.split()returns a list.- All string methods return new strings because strings are immutable.