String Operations
Whitespace Removal
text = '\n x yz \n'
print(text.strip()) # Removes leading and trailing whitespace and newlines
print(text.rstrip()) # Removes trailing whitespace only
print(text.lstrip()) # Removes leading whitespace only
Substitution
print(text.replace('x', 'X')) # Replaces all 'x' characters with 'X'
print(text.replace(' ', '')) # Removes all spaces by replacing them with empty strings
Locating Substrings
sample = 'hello world'
print(sample.find('o')) # Returns -1 if not found
print(sample.index('o')) # Raises ValueError if not found
Prefix and Suffix Checks
filename = 'document.jpg'
print(filename.startswith('doc')) # Checks if string starts with 'doc'
print(filename.endswith('.jpg')) # Checks if string ends with '.jpg'
Counting and Length
phrase = 'character count'
print(phrase.count('c')) # Counts occurrences of 'c'
print(len(phrase)) # Returns total length
Padding and Alignment
print(phrase.center(30, '-')) # Centers string within 30 characters using '-' for padding
print('42'.zfill(5)) # Pads with leading zeros to reach length 5
Case Conversion
mixed = 'PyThOn'
print(mixed.upper()) # Converts to uppercase
print(mixed.lower()) # Converts to lowercase
print(mixed.capitalize()) # Capitalizes first character
print(mixed.title()) # Capitalizes first character of each word
String Type Validation
test1 = 'ABC!123'
test2 = '测试文字'
test3 = '¾123'
print(test1.isupper()) # Checks if all alphabetic characters are uppercase
print(test1.islower()) # Checks if all alphabetic characters are lowercase
print(test2.isalpha()) # Checks if string contains only letters or characters
print(test2.isalnum()) # Checks if string contains only alphanumeric characters
print(test1.isascii()) # Checks if string contains only ASCII characters
print(test3.isdecimal()) # Checks for decimal digits only (0-9)
print(test3.isdigit()) # Checks for digit characters including superscripts
print(test3.isnumeric()) # Checks for numeric characters including fractions
Spiltting and Joining
# Splitting
names = 'alice,bob,charlie,david'
print(names.split(',')) # Splits by comma into list
# Joining
name_list = ['alice', 'bob', 'charlie', 'david']
print('-'.join(name_list)) # Joins list elements with hyphen
String Formatting
# format() method
template = 'User {} logged in at {}'
print(template.format('admin', '14:30'))
# format() with named parameters
query = 'INSERT INTO users(id, name, email) VALUES({id}, {name}, {email})'
print(query.format(id=1, name='john', email='john@example.com'))
# format_map() with dictionary
data = {'id': 2, 'name': 'jane', 'email': 'jane@example.com'}
print(query.format_map(data))
List Operations
Adding Elements
fruits = ['apple', 'banana']
fruits.append('cherry') # Adds to end
fruits.insert(1, 'blueberry') # Inserts at index 1
more_fruits = ['date', 'elderberry']
fruits.extend(more_fruits) # Extends with another list
Accessing Elements
items = [10, 20, 30, 40, 50]
print(items[0]) # First element
print(items[-1]) # Last element
print(items[1:4]) # Slice from index 1 to 3
print(items[::2]) # Every second element
Element Information
values = [5, 2, 8, 2, 9, 2]
print(values.count(2)) # Count occurrences of 2
print(len(values)) # Total number of elements
print(values.index(8)) # First index of 8
Modifying Elements
numbers = [1, 2, 3, 4, 5]
numbers[2] = 99 # Modify single element
numbers[1:3] = [88, 77] # Modify slice
numbers[3:] = [66, 55, 44] # Replace from index 3 onward
Sorting
data = [3, 1, 4, 1, 5, 9]
data.reverse() # Reverse in place
data.sort() # Sort ascending
data.sort(reverse=True) # Sort descending
Removing Elements
items = ['a', 'b', 'c', 'd', 'e']
items.remove('c') # Remove first 'c'
removed = items.pop(1) # Remove and return element at index 1
last = items.pop() # Remove and return last element
del items[0] # Delete element at index 0
Tuple Operations
Tuples are immutable sequences with limited methods:
# Creation and access
config = ('localhost', 'admin', 'secret', 5432)
print(config[0]) # Access by index
print(config[1:3]) # Slicing
# Tuple operations
t1 = (1, 2, 3)
t2 = (4, 5, 6)
combined = t1 + t2 # Concatenation
x, y, z = t1 # Unpacking
# Available methods
print(t2.count(5)) # Count occurrences
print(t2.index(6)) # Find first index
Dictionary Operations
Creation
# Multiple creation methods
user1 = {'name': 'Alice', 'age': 30}
user2 = dict(name='Bob', age=25)
user3 = dict([('name', 'Charlie'), ('age', 35)])
Access and Modification
person = {'name': 'David', 'city': 'London'}
print(person['name']) # Access by key
person['age'] = 28 # Add new key-value pair
person['city'] = 'Paris' # Modify existing value
# Safe access
print(person.get('email', 'N/A')) # Returns 'N/A' if key doesn't exist
# Key operations
print('name' in person) # Check key existence
print(person.keys()) # View all keys
print(person.values()) # View all values
print(person.items()) # View all key-value pairs
Updates and Merging
original = {'a': 1, 'b': 2}
updates = {'b': 3, 'c': 4}
original.update(updates) # Merge dictionaries
Removal
data = {'x': 10, 'y': 20, 'z': 30}
removed = data.pop('y') # Remove and return value for 'y'
last = data.popitem() # Remove and return last inserted item
del data['x'] # Delete specific key
Set Operations
Sets store unique, unordered elements:
# Creation
unique_numbers = {1, 2, 3, 4, 5}
another_set = set([3, 4, 5, 6, 7])
# Basic operations
unique_numbers.add(6) # Add single element
unique_numbers.update([7, 8, 9]) # Add multiple elements
unique_numbers.remove(3) # Remove element (raises error if missing)
unique_numbers.discard(10) # Remove element (no error if missing)
popped = unique_numbers.pop() # Remove and return arbitrary element
# Set operations
print(unique_numbers.union(another_set)) # All elements from both sets
print(unique_numbers.intersection(another_set)) # Common elements
print(unique_numbers.difference(another_set)) # Elements in first not in second
print(unique_numbers.symmetric_difference(another_set)) # Elements in either but not both
# Comparisons
print({1, 2}.issubset({1, 2, 3})) # Check if first is subset of second
print({1, 2, 3}.issuperset({1, 2})) # Check if first is superset of second
print({1, 2}.isdisjoint({3, 4})) # Check if sets have no common elements