String Methods
Common String Methods
Python strings have many built-in methods for manipulation, searching, and validation.
Example
text = "Python Programming"
# Case methods
print(text.lower()) # 'python programming'
print(text.upper()) # 'PYTHON PROGRAMMING'
# Search methods
print(text.find("Pro")) # 7
print("gram" in text) # True
# Utility methods
print(text.split()) # ['Python', 'Programming']
print(text.startswith("Py")) # True
Output
python programming PYTHON PROGRAMMING 7 True ['Python', 'Programming'] True
Method Categories
Category | Methods |
---|---|
Case Conversion | upper(), lower(), title(), capitalize(), swapcase() |
Searching | find(), index(), count(), startswith(), endswith() |
Validation | isalpha(), isdigit(), isalnum(), isspace() |
Trimming & Padding | strip(), lstrip(), rstrip(), zfill(), center() |
Splitting | split(), rsplit(), splitlines(), partition() |
Joining | join() |
Practical Examples
Example
# Password validation example
def is_strong_password(password):
return (len(password) >= 8 and
any(c.isupper() for c in password) and
any(c.isdigit() for c in password))
print(is_strong_password("Pass1234")) # True
# CSV parsing example
csv_data = "name,age,email"
headers = [h.strip() for h in csv_data.split(",")]
print(headers) # ['name', 'age', 'email']
Output
True ['name', 'age', 'email']
ℹ️ Note: String methods can be chained, e.g., text.lower().strip().split()