Strings are one of the most commonly used data types in Python. Python provides a rich set of built-in methods to manipulate strings efficiently. Whether you are formatting text, searching for substrings, or modifying content, Python string methods make it easy.
In this guide, we will explore various Python string methods with practical examples to help you master string manipulation.
lower()
and upper()
These methods are used to convert a string into lowercase or uppercase.
text = "Hello World"
print(text.lower()) # Output: hello world
print(text.upper()) # Output: HELLO WORLD
strip()
, lstrip()
, and rstrip()
These methods remove whitespace from the beginning and/or end of a string
text = " Python "
print(text.strip()) # Output: "Python"
print(text.lstrip()) # Output: "Python "
print(text.rstrip()) # Output: " Python".
find()
and index()
These methods search for a substring within a string. If found, they return the index of the first occurrence.
text = "Python programming"
print(text.find("gram")) # Output: 7
print(text.index("gram")) # Output: 7
replace()
Replaces occurrences of a substring with another string.
text = "I love Python"
print(text.replace("love", "like")) # Output: I like Python
split()
Splits a string into a list based on a delimiter.
text = "apple,banana,grape"
print(text.split(",")) # Output: ['apple', 'banana', 'grape']
join()
Joins elements of a list into a string with a specified separator.
words = ["Python", "is", "fun"]
print(" ".join(words)) # Output: Python is fun
startswith()
and endswith()
These methods check if a string starts or ends with a particular substring.
text = "hello world"
print(text.startswith("hello")) # Output: True
print(text.endswith("world")) # Output: True
isalpha()
, isdigit()
, and isalnum()
These methods check if a string contains only letters, digits, or alphanumeric characters.
print("Python".isalpha()) # Output: True
print("1234".isdigit()) # Output: True
print("Python123".isalnum()) # Output: True
Python string methods provide powerful tools for text manipulation. Whether you are formatting text, searching for substrings, or splitting and joining content, these built-in functions simplify complex tasks.
Mastering these string methods will help you write cleaner and more efficient Python code!