The Python Standard Library is a collection of modules and packages that come bundled with Python. These modules provide a wide range of functionalities, such as file I/O, system calls, data manipulation, mathematical operations, and more. By using standard library, you can perform many common tasks without needing to install additional packages.
Here’s some of the most commonly used standard library modules:
The sys module provides access to some variables used or maintained by the Python interpreter and to functions that interact with the interpreter.
Common Uses:
Example:
import sys
# Command-line arguments
print(sys.argv)
# Exit the program
sys.exit()
The os module provides a way of using operating system-dependent functionality like reading or writing to the file system.
Common Uses:
Example:
import os
# Get the current working directory
print(os.getcwd())
# List files in a directory
print(os.listdir('.'))
# Create a new directory
os.mkdir('new_directory')
# Remove a directory
os.rmdir('new_directory')
The math module provides access to mathematical functions.
Common Uses:
Example:
import math
# Calculate the square root
print(math.sqrt(16)) # Output: 4.0
# Trigonometric functions
print(math.sin(math.pi / 2)) # Output: 1.0
# Constants
print(math.pi) # Output: 3.141592653589793
print(math.e) # Output: 2.718281828459045
The datetime module supplies classes for manipulating dates and times.
Common Uses:
Example:
from datetime import datetime, timedelta
# Current date and time
now = datetime.now()
print(now)
# Formatting date and time
formatted_now = now.strftime('%Y-%m-%d %H:%M:%S')
print(formatted_now)
# Date arithmetic
future_date = now + timedelta(days=5)
print(future_date)
The random module implements pseudo-random number generators for various distributions.
Common Uses:
Example:
import random
# Random integer
print(random.randint(1, 10))
# Random choice
choices = ['apple', 'banana', 'cherry']
print(random.choice(choices))
# Shuffling a list
random.shuffle(choices)
print(choices)
The re module provides support for regular expressions.
Common Uses:
Example:
import re
# Search for a pattern
pattern = r'\d+'
text = 'There are 42 apples'
match = re.search(pattern, text)
if match:
print(match.group()) # Output: 42
# Replace a pattern
new_text = re.sub(pattern, 'many', text)
print(new_text) # Output: There are many apples