Python26 min read
Python String Methods
Master string methods: case conversion, searching, replacing, splitting/joining, trimming, checking, and practical text-cleaning patterns.
Michael Brown
July 23, 2025
13.2k494
Strings are everywhere: names, emails, logs, files, messages, and API responses.
Important concept:
Strings are **immutable**. That means methods return a **new** string, they do not change the original string.
## Case conversion
```python
text = "Hello World"
print(text.upper())
print(text.lower())
print(text.capitalize())
print(text.title())
print(text.swapcase())
```
Expected output:
```
HELLO WORLD
hello world
Hello world
Hello World
hELLO wORLD
```
## Finding and counting
```python
text = "Python is awesome. Python is easy."
print(text.find("Python"))
print(text.find("Python", 10))
print(text.find("Java"))
print(text.count("Python"))
```
Expected output:
```
0
19
-1
2
```
## Replacing
```python
text = "I love Python"
new_text = text.replace("love", "enjoy")
print(text)
print(new_text)
```
Expected output:
```
I love Python
I enjoy Python
```
Replace only first N occurrences:
```python
text = "ha ha ha"
print(text.replace("ha", "he", 2))
```
Expected output:
```
he he ha
```
## Splitting and joining (very practical)
```python
csv = "apple,banana,orange"
fruits = csv.split(",")
print(fruits)
cities = ["Miami", "Austin", "Denver"]
text = ", ".join(cities)
print(text)
```
Expected output:
```
['apple', 'banana', 'orange']
Miami, Austin, Denver
```
## Trimming spaces
```python
text = " hello "
print(text.strip())
print(text.lstrip())
print(text.rstrip())
```
Expected output:
```
hello
hello
hello
```
## Checking content (validation)
```python
print("hello".isalpha())
print("123".isdigit())
print("hello123".isalnum())
print("HELLO".isupper())
print("hello".islower())
```
Expected output:
```
True
True
True
True
True
```
## Real pattern: clean user input
```python
raw = " SARAH.JOHNSON@EXAMPLE.COM "
clean = raw.strip().lower()
print(clean)
```
Expected output:
```
sarah.johnson@example.com
```
## Graph: string cleaning pipeline
```mermaid
flowchart LR
A[Raw input] --> B[strip spaces]
B --> C[lower/upper]
C --> D[replace/split]
D --> E[Clean output]
```
You now have a strong foundation of practical string methods and patterns used in real applications.
#Python#Intermediate#Strings