Python String Built-in Functions with Examples
1. len() - Returns the length of a string.
print(len("Hello")) # Output: 5
2. upper() - Converts all characters to uppercase.
print("hello".upper()) # Output: "HELLO"
3. lower() - Converts all characters to lowercase.
print("HELLO".lower()) # Output: "hello"
4. capitalize() - Capitalizes the first letter of the string.
print("hello world".capitalize()) # Output: "Hello world"
5. title() - Capitalizes the first letter of each word.
print("hello world".title()) # Output: "Hello World"
6. strip() - Removes leading and trailing whitespace.
print(" hello ".strip()) # Output: "hello"
7. lstrip() - Removes leading whitespace.
print(" hello ".lstrip()) # Output: "hello "
8. rstrip() - Removes trailing whitespace.
print(" hello ".rstrip()) # Output: " hello"
9. replace() - Replaces a substring with another substring.
print("hello world".replace("world", "Python")) # Output: "hello Python"
10. find() - Returns the index of the first occurrence of a substring.
print("hello world".find("world")) # Output: 6
11. rfind() - Returns the index of the last occurrence of a substring.
print("hello world world".rfind("world")) # Output: 12
12. index() - Returns the index of the first occurrence of a substring (raises an error if not found).
print("hello world".index("world")) # Output: 6
13. rindex() - Returns the index of the last occurrence of a substring (raises an error if not found).
print("hello world world".rindex("world")) # Output: 12
14. startswith() - Checks if the string starts with a given substring.
print("hello world".startswith("hello")) # Output: True
15. endswith() - Checks if the string ends with a given substring.
print("hello world".endswith("world")) # Output: True
16. split() - Splits the string into a list based on a separator.
print("hello world".split()) # Output: ['hello', 'world']
17. rsplit() - Splits the string from the right side.
print("apple,banana,grape".rsplit(",", 1)) # Output: ['apple,banana', 'grape']
18. join() - Joins elements of an iterable with a separator.
print("-".join(["hello", "world"])) # Output: "hello-world"
19. isalpha() - Checks if all characters are alphabets.
print("hello".isalpha()) # Output: True
20. isdigit() - Checks if all characters are digits.
print("123".isdigit()) # Output: True
21. isalnum() - Checks if all characters are alphanumeric (letters and numbers only).
print("hello123".isalnum()) # Output: True