String Manipulation
Working with text - formatting, methods, and string operations.
String Basics
- Strings are sequences of characters.
- Use single or double quotes.
- Triple quotes for multi-line strings.
- Strings are immutable.
# Creating strings
name = 'Alice'
message = "Hello, World!"
multi = '''This is
a multi-line
string'''
# Concatenation
greeting = "Hello" + " " + "World"
print(greeting) # Hello World
# Repetition
laugh = "ha" * 3
print(laugh) # hahaha
String Formatting
- f-strings (Python 3.6+): Most readable and efficient.
- format() method: Older but still useful.
- % operator: Legacy formatting.
name = "Alice"
age = 25
# f-strings (recommended)
msg = f"My name is {name} and I'm {age} years old"
print(msg)
# format() method
msg = "My name is {} and I'm {} years old".format(name, age)
print(msg)
# With expressions
x = 10
y = 20
print(f"Sum: {x + y}") # Sum: 30
String Methods
- upper(), lower(): Change case
- strip(): Remove whitespace
- split(): Split into list
- replace(): Replace substring
- find(): Find substring position
text = " Hello, World! "
print(text.upper()) # " HELLO, WORLD! "
print(text.lower()) # " hello, world! "
print(text.strip()) # "Hello, World!"
print(text.replace("World", "Python")) # " Hello, Python! "
# Split and join
words = "apple,banana,cherry".split(",")
print(words) # ['apple', 'banana', 'cherry']
joined = " ".join(words)
print(joined) # "apple banana cherry"
String Slicing
- Access parts of strings using [start:end].
- Negative indices count from the end.
- Step parameter for skipping characters.
text = "Python Programming"
print(text[0:6]) # "Python"
print(text[7:]) # "Programming"
print(text[:6]) # "Python"
print(text[-11:]) # "Programming"
# Every other character
print(text[::2]) # "Pto rgamn"
# Reverse string
print(text[::-1]) # "gnimmargorP nohtyP"
String Checking
- startswith(), endswith(): Check prefix/suffix
- isdigit(), isalpha(): Check character types
- in operator: Check if substring exists
text = "Python3"
print(text.startswith("Py")) # True
print(text.endswith("on")) # False
print(text.isdigit()) # False
print("123".isdigit()) # True
print(text.isalpha()) # False
# Membership
print("Py" in text) # True
print("Java" in text) # False