Python String Methods

Comprehensive guide to Python string manipulation methods and operations.

String Basics

# Creating strings
text = 'Hello World'
text2 = "Python Programming"
multiline = """Line 1
Line 2
Line 3"""

# String length
len(text)  # 11

# String concatenation
full = text + ' - ' + text2  # Hello World - Python Programming

Case Methods

text = 'Hello World'

text.upper()  # HELLO WORLD
text.lower()  # hello world
text.title()  # Hello World
text.capitalize()  # Hello world
text.swapcase()  # hELLO wORLD

Search & Replace

text = 'Hello World Python'

# Find substring
text.find('World')  # 6 (index position)
text.find('Java')  # -1 (not found)
text.index('World')  # 6 (raises error if not found)

# Check if contains
'World' in text  # True
'Java' not in text  # True

# Replace
text.replace('World', 'Universe')  # Hello Universe Python
text.replace('l', 'L', 2)  # HeLLo World Python (replace first 2)

Split & Join

# Split string
text = 'apple,banana,orange'
fruits = text.split(',')  # ['apple', 'banana', 'orange']

sentence = 'Hello World Python'
words = sentence.split()  # ['Hello', 'World', 'Python'] (splits on whitespace)

# Join list into string
fruits = ['apple', 'banana', 'orange']
','.join(fruits)  # apple,banana,orange
' - '.join(fruits)  # apple - banana - orange

Strip & Format

# Remove whitespace
text = '  Hello World  '
text.strip()  # 'Hello World' (both sides)
text.lstrip()  # 'Hello World  ' (left side)
text.rstrip()  # '  Hello World' (right side)

# Check string properties
'123'.isdigit()  # True
'abc'.isalpha()  # True
'abc123'.isalnum()  # True (alphanumeric)
'HELLO'.isupper()  # True
'hello'.islower()  # True

String Slicing

text = 'Python Programming'

# Basic slicing
text[0]  # 'P' (first character)
text[-1]  # 'g' (last character)
text[0:6]  # 'Python'
text[7:]  # 'Programming'
text[:6]  # 'Python'

# Step slicing
text[::2]  # 'Pto rgamn' (every 2nd char)
text[::-1]  # 'gnimmargorP nohtyP' (reverse)