Python Strings : String Methods
Python provides a rich set of string methods to manipulate, modify, and analyze strings. These methods help you perform common tasks like searching, formatting, changing case, and more. Below is a list of commonly used string methods in Python with examples.
1. upper()
Converts all characters in the string to uppercase.
text = "hello world"
result = text.upper()
print(result) # Output: "HELLO WORLD"
2. lower()
Converts all characters in the string to lowercase.
text = "HELLO WORLD"
result = text.lower()
print(result) # Output: "hello world"
3. capitalize()
Capitalizes the first character of the string and converts the rest to lowercase.
text = "hello world"
result = text.capitalize()
print(result) # Output: "Hello world"
4. title()
Converts the first character of each word to uppercase.
text = "hello world"
result = text.title()
print(result) # Output: "Hello World"
5. strip()
Removes leading and trailing whitespace characters (or other specified characters).
text = " hello world "
result = text.strip()
print(result) # Output: "hello world"
You can also remove specific characters by passing them as an argument:
text = "###hello world###"
result = text.strip('#')
print(result) # Output: "hello world"
6. lstrip() and rstrip()
Removes leading (left) or trailing (right) whitespace or specified characters.
text = " hello world "
print(text.lstrip()) # Output: "hello world "
print(text.rstrip()) # Output: " hello world"
7. split()
Splits the string into a list of substrings based on a delimiter (default is whitespace).
text = "hello world python"
result = text.split()
print(result) # Output: ['hello', 'world', 'python']
# Split by a specific delimiter
text = "apple,banana,cherry"
result = text.split(',')
print(result) # Output: ['apple', 'banana', 'cherry']
8. join()
Joins a list of strings into a single string, with a specified separator.
words = ['hello', 'world', 'python']
result = " ".join(words)
print(result) # Output: "hello world python"
9. replace()
Replaces occurrences of a substring with another substring.
text = "hello world"
result = text.replace("world", "python")
print(result) # Output: "hello python"
10. find()
Returns the index of the first occurrence of a substring. Returns -1 if the substring is not found.
text = "hello world"
index = text.find("world")
print(index) # Output: 6
index = text.find("python")
print(index) # Output: -1
11. index()
Similar to find(), but raises a ValueError if the substring is not found.
text = "hello world"
index = text.index("world")
print(index) # Output: 6
# Raises ValueError if the substring is not found
# text.index("python") # ValueError: substring not found
12. startswith() and endswith()
Checks if the string starts or ends with a particular substring.
text = "hello world"
print(text.startswith("hello")) # Output: True
print(text.endswith("world")) # Output: True
13. count()
Returns the number of occurrences of a substring in the string.
text = "hello hello world"
count = text.count("hello")
print(count) # Output: 2
14. isalpha()
Checks if all characters in the string are alphabetic.
text = "hello"
print(text.isalpha()) # Output: True
text = "hello123"
print(text.isalpha()) # Output: False
15. isdigit()
Checks if all characters in the string are digits.
text = "12345"
print(text.isdigit()) # Output: True
text = "12345abc"
print(text.isdigit()) # Output: False
16. isalnum()
Checks if all characters in the string are alphanumeric (letters and numbers).
text = "hello123"
print(text.isalnum()) # Output: True
text = "hello 123"
print(text.isalnum()) # Output: False (space is not alphanumeric)
17. isspace()
Checks if the string consists only of whitespace characters.
text = " "
print(text.isspace()) # Output: True
text = "hello world"
print(text.isspace()) # Output: False
18. swapcase()
Converts uppercase characters to lowercase and lowercase characters to uppercase.
text = "Hello World"
result = text.swapcase()
print(result) # Output: "hELLO wORLD"
19. zfill()
Pads the string on the left with zeros until it reaches a specified length.
text = "42"
result = text.zfill(5)
print(result) # Output: "00042"
20. center(), ljust(), and rjust()
center(): Centers the string in a field of a specified width.ljust(): Left-justifies the string.rjust(): Right-justifies the string.
text = "hello"
print(text.center(10, '-')) # Output: "--hello---"
print(text.ljust(10, '-')) # Output: "hello-----"
print(text.rjust(10, '-')) # Output: "-----hello"
21. format()
Inserts values into placeholders within the string.
name = "John"
age = 30
result = "My name is {} and I am {} years old.".format(name, age)
print(result) # Output: "My name is John and I am 30 years old."
22. partition() and rpartition()
Splits the string at the first (or last) occurrence of a specified separator, returning a tuple of three parts: the part before the separator, the separator itself, and the part after the separator.
text = "hello world"
result = text.partition(" ")
print(result) # Output: ('hello', ' ', 'world')
result = text.rpartition(" ")
print(result) # Output: ('hello', ' ', 'world')
These are just a few of the powerful string methods Python provides.