This page covers some essential string operations that are useful in daily Python programming.
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)
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
text = " Hello World! "
print(text.strip()) # Output: "Hello World!"
print(text.lstrip()) # Output: "Hello World! "
print(text.rstrip()) # Output: " Hello World!"
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"
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