Chapter 3: Strings and Loops / Lesson 17

String Methods in Python

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:

case_methods.py
text = "Hello World" print(text.upper()) # HELLO WORLD print(text.lower()) # hello world print(text.title()) # Hello World print(text.capitalize()) # Hello world print(text.swapcase()) # hELLO wORLD # Original string is unchanged print(text) # Hello World

Searching and Finding

Methods to search for substrings within a string:

search_methods.py
text = "Hello World" print(text.find("World")) # 6 (index where found) print(text.find("Python")) # -1 (not found) print(text.index("World")) # 6 print(text.count("l")) # 3 (number of occurrences) print("Hello" in text) # True print(text.startswith("Hello")) # True print(text.endswith("World")) # True

Modifying Strings

Methods that create modified versions of strings:

modify_methods.py
text = "Hello World" # Replace substrings print(text.replace("World", "Python")) # Hello Python # Strip whitespace whitespace_text = " Hello World " print(whitespace_text.strip()) # "Hello World" print(whitespace_text.lstrip()) # "Hello World " print(whitespace_text.rstrip()) # " Hello World" # Split into list print(text.split()) # ['Hello', 'World'] print(text.split("l")) # ['He', '', 'o Wor', 'd'] # Join list into string words = ["Hello", "World"] print("-".join(words)) # Hello-World

Checking String Properties

Methods that check properties of strings and return boolean values:

check_methods.py
text1 = "Hello123" text2 = "WORLD" text3 = "hello" text4 = " " print(text1.isalnum()) # True (letters or digits) print(text1.isalpha()) # False (only letters) print(text1.isdigit()) # False (only digits) print(text2.isupper()) # True print(text3.islower()) # True print(text4.isspace()) # True (only whitespace)

Formatting Strings

Python offers multiple ways to format strings. F-strings (f-strings) are the most modern and recommended:

formatting.py
name = "Alice" age = 25 # F-strings (recommended) message = f"Hello, {name}! You are {age} years old." print(message) # String formatting message2 = "Hello, {}! You are {} years old.".format(name, age) print(message2) # Format with width and precision pi = 3.14159 print(f"Pi is approximately {pi:.2f}") # Pi is approximately 3.14

Common String Operations

Combining multiple string methods for practical tasks:

common_ops.py
# Clean user input user_input = " Hello World " cleaned = user_input.strip().lower() print(cleaned) # "hello world" # Check if string contains specific pattern email = "user@example.com" if "@" in email and email.endswith(".com"): print("Valid email format") # Get string length text = "Hello World" print(len(text)) # 11 # Access characters by index print(text[0]) # H print(text[-1]) # d (last character)

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.

main.py
📤 Output
Click "Run" to execute...