Python String Operations Reference
By Engr Aamir Jamil
String Creation and Basic Operations
Creating Strings
python
# Different ways to create strings
single_quote = 'Hello World'
double_quote = "Hello World"
triple_quote = """Multi-line
string example"""
raw_string = r"C:\Users\Name\[Link]" # Raw string
f_string = f"Hello {name}" # Formatted string
String Indexing and Slicing
python
text = "Python Programming"
# Indexing
first_char = text[0] # 'P'
last_char = text[-1] # 'g'
# Slicing [start:end:step]
substring = text[0:6] # 'Python'
reverse = text[::-1] # 'gnimmargorP nohtyP'
every_second = text[::2] # 'Pto rgamn'
String Methods - Case Operations
Case Conversion
python
text = "Python Programming"
# Case methods
upper_text = [Link]() # 'PYTHON PROGRAMMING'
lower_text = [Link]() # 'python programming'
title_text = [Link]() # 'Python Programming'
capitalize_text = [Link]() # 'Python programming'
swapcase_text = [Link]() # 'pYTHON pROGRAMMING'
Case Checking
python
text = "Hello123"
# Check case methods
[Link]() # False
[Link]() # False
[Link]() # True
[Link]() # False (contains numbers)
[Link]() # False
[Link]() # True (alphanumeric)
String Methods - Searching and Finding
Finding Substrings
python
text = "Python is awesome and Python is powerful"
# Find methods
index = [Link]("Python") # 0 (first occurrence)
last_index = [Link]("Python") # 22 (last occurrence)
count = [Link]("Python") #2
# Check if string contains
contains = "awesome" in text # True
starts = [Link]("Python") # True
ends = [Link]("powerful") # True
Replace Operations
python
text = "Hello World Hello"
# Replace methods
new_text = [Link]("Hello", "Hi") # 'Hi World Hi'
first_only = [Link]("Hello", "Hi", 1) # 'Hi World Hello'
String Methods - Splitting and Joining
Splitting Strings
python
text = "apple,banana,orange"
csv_text = "name:age:city"
# Split methods
fruits = [Link](",") # ['apple', 'banana', 'orange']
parts = csv_text.split(":") # ['name', 'age', 'city']
words = "hello world".split() # ['hello', 'world'] (default whitespace)
lines = "line1\nline2\nline3".splitlines() # ['line1', 'line2', 'line3']
# Partition (splits into 3 parts)
before, sep, after = "name@[Link]".partition("@") # 'name', '@', '[Link]'
Joining Strings
python
# Join method
fruits = ["apple", "banana", "orange"]
joined = ", ".join(fruits) # 'apple, banana, orange'
path = "/".join(["home", "user", "documents"]) # 'home/user/documents'
String Methods - Whitespace Operations
Whitespace Handling
python
text = " Hello World "
# Remove whitespace
stripped = [Link]() # 'Hello World'
left_strip = [Link]() # 'Hello World '
right_strip = [Link]() # ' Hello World'
# Remove specific characters
cleaned = "...Hello...".strip(".") # 'Hello'
Padding and Alignment
python
text = "Python"
# Padding methods
left_pad = [Link](10, "-") # 'Python----'
right_pad = [Link](10, "-") # '----Python'
center_pad = [Link](10, "-") # '--Python--'
zero_pad = "42".zfill(5) # '00042'
String Formatting
Old Style Formatting (% operator)
python
name = "Aamir"
age = 30
text = "My name is %s and I am %d years old" % (name, age)
.format() Method
python
# Positional arguments
text = "Hello {0}, you are {1} years old".format("Aamir", 30)
# Named arguments
text = "Hello {name}, you are {age} years old".format(name="Aamir", age=30)
# Number formatting
price = 19.99
formatted = "Price: ${:.2f}".format(price) # 'Price: $19.99'
F-Strings (Recommended - Python 3.6+)
python
name = "Aamir"
age = 30
price = 19.99
# Basic f-string
text = f"Hello {name}, you are {age} years old"
# With expressions
text = f"Next year you'll be {age + 1}"
# With formatting
text = f"Price: ${price:.2f}"
# With method calls
text = f"Name in caps: {[Link]()}"
Advanced String Operations
String Validation Methods
python
text = "Hello123"
# Character type checking
[Link]() # False (contains numbers)
[Link]() # False (contains letters)
[Link]() # True (alphanumeric)
[Link]() # False
[Link]() # True
[Link]() # False (not valid Python identifier)
String Translation
python
# Create translation table
translator = [Link]("aeiou", "12345")
text = "hello world"
translated = [Link](translator) # 'h2ll4 w4rld'
# Remove characters
remove_vowels = [Link]("", "", "aeiou")
no_vowels = "hello world".translate(remove_vowels) # 'hll wrld'
String Encoding/Decoding
python
text = "Hello World"
# Encode to bytes
encoded = [Link]('utf-8') # b'Hello World'
encoded_latin = [Link]('latin-1')
# Decode from bytes
decoded = [Link]('utf-8') # 'Hello World'
String Constants (from string module)
python
import string
# Useful string constants
string.ascii_letters # 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.ascii_lowercase # 'abcdefghijklmnopqrstuvwxyz'
string.ascii_uppercase # 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
[Link] # '0123456789'
[Link] # '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
[Link] # ' \t\n\r\x0b\x0c'
Performance Tips
String Concatenation
python
# Inefficient (creates new string objects)
result = ""
for i in range(1000):
result += str(i)
# Efficient (use join)
numbers = [str(i) for i in range(1000)]
result = "".join(numbers)
# For few strings, + is fine
result = "Hello" + " " + "World"
String Comparison
python
# Case-insensitive comparison
[Link]() == [Link]()
# Check if string is empty
if not text: # Better than if text == ""
print("String is empty")
Master these string operations for efficient text processing in Python