Python String Methods 🧵
String Methods Reference
Python has a rich set of built-in methods for string manipulation. All string methods return new values - they don't change the original string (strings are immutable).
✨ Most Commonly Used
python
# upper() / lower() / capitalize()
text = "Hello World"
print(text.upper()) # "HELLO WORLD"
print(text.lower()) # "hello world"
print(text.capitalize()) # "Hello world"python
# strip() / replace() / split()
text = " hello "
print(text.strip()) # "hello"
print(text.replace("h", "H")) # " Hello "
print("a-b-c".split("-")) # ['a', 'b', 'c']📋 Complete Method Reference
| Method | Description |
|---|---|
| capitalize() | Converts the first character to upper case |
| casefold() | Converts string into lower case (aggressive, for case-insensitive comparisons) |
| center() | Returns a centered string |
| count() | Returns the number of times a specified value occurs in a string |
| endswith() | Returns true if the string ends with the specified value |
| find() | Searches the string for a specified value and returns the position (returns -1 if not found) |
| format() | Formats specified values in a string |
| index() | Like find(), but raises ValueError if not found |
| isalnum() | Returns True if all characters in the string are alphanumeric |
| isalpha() | Returns True if all characters in the string are in the alphabet |
| isdigit() | Returns True if all characters in the string are dig its |
| islower() | Returns True if all characters in the string are lower case |
| isupper() | Returns True if all characters in the string are upper case |
| join() | Joins the elements of an iterable to the end of the string |
| lower() | Converts a string into lower case |
| lstrip() | Returns a left trim version of the string |
| replace() | Returns a string where a specified value is replaced with a specified value |
| split() | Splits the string at the specified separator, and returns a list |
| startswith() | Returns true if the string starts with the specified value |
| strip() | Returns a trimmed version of the string |
| upper() | Converts a string into upper case |
✨ Pro Tip
Use find() when you want to handle "not found" gracefully, and index() when you expect the value to always be there (it will raise an error if not).