Important String Operations in Python

Overview

This page covers some essential string operations that are useful in daily Python programming.

1. Checking if a String Contains a Substring

text = "Python is awesome"

# Using 'in' keyword
print("awesome" in text)    # Output: True

# Using find() method
print(text.find("is"))      # Output: 7 (index where substring starts)
print(text.find("java"))    # Output: -1 (not found)

2. Changing Case

text = "Python is awesome"

print(text.upper())    # Output: PYTHON IS AWESOME
print(text.lower())    # Output: python is awesome
print(text.title())    # Output: Python Is Awesome
print(text.capitalize()) # Output: Python is awesome
print(text.swapcase()) # Output: pYTHON IS AWESOME

3. Trimming Whitespace

text = "   Hello World!   "

print(text.strip())    # Output: "Hello World!"
print(text.lstrip())   # Output: "Hello World!   "
print(text.rstrip())   # Output: "   Hello World!"

4. Splitting and Joining Strings

text = "apple,banana,cherry"

# Split by comma
fruits = text.split(",")
print(fruits)              # Output: ['apple', 'banana', 'cherry']

# Join with space
joined_text = " ".join(fruits)
print(joined_text)         # Output: "apple banana cherry"

5. Replacing Substrings

text = "I like apples"

# Replace apples with oranges
new_text = text.replace("apples", "oranges")
print(new_text)             # Output: I like oranges

# Replace only first occurrence
text2 = "spam spam spam"
print(text2.replace("spam", "eggs", 2))  # Output: eggs eggs spam