Python String Methods and Character Functions
Explain 1. ord() and chr(), 2. in and not in Operators
1. ord() and chr() Functions
Python provides the ord() and chr() functions for converting between characters and their Unicode values.
- ord() converts a character into its corresponding Unicode (ASCII) integer value.
- chr() converts a Unicode integer value into its corresponding character.
These functions are useful in character manipulation, encoding, encryption, and text processing applications.
Example
print(ord('A'))print(ord('a'))print(chr(65))print(chr(97))
Output
65
97
A
a
2. in and not in Operators on Strings
The in and not in operators are called membership operators in Python. They are used to check whether a character, word, or substring exists in a string.
- in returns
Trueif the specified value is found in the string. - not in returns
Trueif the specified value is not found in the string.
These operators help in searching, validation, and filtering text data.
Example
s = "Python Programming"print("Python" in s)print("Java" in s)print("Java" not in s)print("Python" not in s)
Output
True
False
True
False
Explain String Methods: title, startswith, and more
This section explains the following string methods: 1. title(), 2. startswith(), 3. zfill(), 4. strip(), 5. ljust(), and 6. rindex().
1. title()
The title() method converts the first character of each word in a string to uppercase and the remaining characters to lowercase.
Syntax: string.title()
Example
s = "python programming language"print(s.title())
Output
Python Programming Language
2. startswith()
The startswith() method checks whether a string begins with a specified prefix. It returns True or False.
Syntax: string.startswith(prefix)
Example
s = "Python Programming"print(s.startswith("Python"))
Output
True
3. zfill()
The zfill() method adds zeros (0) at the beginning of a string until it reaches the specified length.
Syntax: string.zfill(width)
Example
s = "25"print(s.zfill(5))
Output
00025
Application: Used for formatting numbers, account numbers, and IDs.
4. strip()
The strip() method removes spaces or specified characters from both ends of a string.
Syntax: string.strip()
Example
s = " Python "print(s.strip())
Output
Python
5. ljust()
The ljust() method left-aligns a string within a specified width and fills the remaining space with a specified character (default is space).
Syntax: string.ljust(width, fillchar)
Example
s = "Python"print(s.ljust(10, '*'))
Output
Python****
6. rindex()
The rindex() method returns the highest (rightmost) position of the specified substring in a string. If the substring is not found, it generates an error.
Syntax: string.rindex(substring)
Example
s = "Python is easy, Python is powerful"print(s.rindex("Python"))
Output
16
English with a size of 4.03 KB