Python String Methods
Master all important string methods in Python.
All important string operations.
Case Conversion
```python text = "Hello World"
print(text.upper()) # HELLO WORLD print(text.lower()) # hello world print(text.capitalize()) # Hello world print(text.title()) # Hello World print(text.swapcase()) # hELLO wORLD ```
Finding and Counting
```python text = "Python is awesome. Python is easy."
Find position print(text.find("Python")) # 0 (first occurrence) print(text.find("Python", 10)) # 19 (search from index 10) print(text.find("Java")) # -1 (not found)
Count occurrences print(text.count("Python")) # 2 ```
Replacing
```python text = "I love Python"
Replace new_text = text.replace("love", "enjoy") print(new_text) # I enjoy Python
Replace first N occurrences text = "ha ha ha" print(text.replace("ha", "he", 2)) # he he ha ```
Splitting and Joining
```python # Split text = "apple,banana,orange" fruits = text.split(",") print(fruits) # ['apple', 'banana', 'orange']
Join cities = ["Miami", "Austin", "Denver"] text = ", ".join(cities) print(text) # Miami, Austin, Denver ```
Trimming
```python text = " hello "
print(text.strip()) # "hello" print(text.lstrip()) # "hello " print(text.rstrip()) # " hello" ```
Checking
```python print("hello".isalpha()) # True print("123".isdigit()) # True print("hello123".isalnum()) # True print("HELLO".isupper()) # True print("hello".islower()) # True ```
Remember
- Strings are immutable - Methods return new strings - Use split() and join() together