python

Standard library modules


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:

 

1. ‘sys’ Module

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:

  • Command-line arguments
  • Interacting with the Python runtime environment

Example:

import sys
# Command-line arguments
print(sys.argv)
# Exit the program
sys.exit()
 

 

2. 'os' Module

The os module provides a way of using operating system-dependent functionality like reading or writing to the file system.

Common Uses:

  • File and directory operations
  • Environment variables
  • Process management

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')
 

 

3. math Module

The math module provides access to mathematical functions.

Common Uses:

  • Mathematical calculations
  • Constants like π and e

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
 

 

4. ‘datetime’ Module

The datetime module supplies classes for manipulating dates and times.

Common Uses:

  • Working with dates and times
  • Formatting dates and times

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)
 

 

5. 'random' Module

The random module implements pseudo-random number generators for various distributions.

Common Uses:

  • Generating random numbers
  • Random choices

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)
 

 

6. 're' Module

The re module provides support for regular expressions.

Common Uses:

  • Pattern matching
  • Searching and replacing

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
 

 


python