String Methods in Python
Strings in Python are objects with many built-in methods that allow you to manipulate and work with text data. These methods make string processing easy and intuitive.
String methods return new strings (strings are immutable in Python) and don't modify the original string. This is important to remember when working with string operations.
Case Conversion Methods
These methods change the case of characters in a string:
text = "Hello World"
print(text.upper())
print(text.lower())
print(text.title())
print(text.capitalize())
print(text.swapcase())
print(text)
Searching and Finding
Methods to search for substrings within a string:
text = "Hello World"
print(text.find("World"))
print(text.find("Python"))
print(text.index("World"))
print(text.count("l"))
print("Hello" in text)
print(text.startswith("Hello"))
print(text.endswith("World"))
Modifying Strings
Methods that create modified versions of strings:
text = "Hello World"
print(text.replace("World", "Python"))
whitespace_text = " Hello World "
print(whitespace_text.strip())
print(whitespace_text.lstrip())
print(whitespace_text.rstrip())
print(text.split())
print(text.split("l"))
words = ["Hello", "World"]
print("-".join(words))
Checking String Properties
Methods that check properties of strings and return boolean values:
text1 = "Hello123"
text2 = "WORLD"
text3 = "hello"
text4 = " "
print(text1.isalnum())
print(text1.isalpha())
print(text1.isdigit())
print(text2.isupper())
print(text3.islower())
print(text4.isspace())
Formatting Strings
Python offers multiple ways to format strings. F-strings (f-strings) are the most modern and recommended:
name = "Alice"
age = 25
message = f"Hello, {name}! You are {age} years old."
print(message)
message2 = "Hello, {}! You are {} years old.".format(name, age)
print(message2)
pi = 3.14159
print(f"Pi is approximately {pi:.2f}")
Common String Operations
Combining multiple string methods for practical tasks:
user_input = " Hello World "
cleaned = user_input.strip().lower()
print(cleaned)
email = "user@example.com"
if "@" in email and email.endswith(".com"):
print("Valid email format")
text = "Hello World"
print(len(text))
print(text[0])
print(text[-1])
Important Notes
💡 Strings Are Immutable
String methods return new strings. The original string remains unchanged. To modify a string, you need to reassign it: text = text.upper()
💡 Method Chaining
You can chain multiple methods together: text.strip().lower().replace(" ", "-")
💡 F-Strings Are Best
For Python 3.6+, use f-strings for string formatting. They're faster, more readable, and less error-prone than other methods.
🎉
Lesson Complete!
Great work! Continue to the next lesson.