Python comes with a rich Standard Library that allows developers to perform common tasks without installing external packages.
datetime ModuleUsed to work with dates and time.
datetimedatetimetimedeltafrom datetime import datetime
now = datetime.now()
print(now)
print(now.strftime("%d-%m-%Y %H:%M:%S"))
from datetime import timedelta
future_date = now + timedelta(days=10)
print(future_date)
math ModuleProvides mathematical functions.
import math
print(math.sqrt(16))
print(math.pow(2, 3))
print(math.factorial(5))
print(math.ceil(4.3))
print(math.floor(4.9))
print(math.pi)
print(math.e)
random ModuleUsed to generate random numbers.
import random
print(random.randint(1, 10))
print(random.random())
colors = ["red", "blue", "green"]
print(random.choice(colors))
random.shuffle(colors)
print(colors)
os & sys Modulesos ModuleUsed to interact with operating system.
import os
print(os.getcwd())
os.mkdir("test_folder")
os.rename("test_folder", "demo")
os.remove("file.txt")
print(os.environ)
sys ModuleUsed for system-level operations.
import sys
print(sys.version)
print(sys.argv)
sys.exit()
shutil ModuleUsed for high-level file operations.
import shutil
shutil.copy("source.txt", "destination.txt")
shutil.copytree("src", "backup")
shutil.rmtree("backup")
re (Regular Expressions)Used for pattern matching and text processing.
findall()search()match()sub()import re
text = "My number is 9876543210"
result = re.findall(r"\d+", text)
print(result)
if re.search(r"\d{10}", text):
print("Valid phone number")
data = "Python is easy"
print(re.sub("easy", "powerful", data))
collections ModuleProvides specialized data structures.
from collections import Counter
nums = [1, 2, 2, 3, 3, 3]
print(Counter(nums))
from collections import defaultdict
d = defaultdict(int)
d["a"] += 1
print(d)
from collections import deque
dq = deque([1, 2, 3])
dq.appendleft(0)
dq.pop()
print(dq)
itertools ModuleProvides fast, memory-efficient iterators.
from itertools import count
for i in count(1):
if i == 5:
break
print(i)
from itertools import cycle
colors = ["red", "blue"]
for color in cycle(colors):
print(color)
break
from itertools import combinations
nums = [1, 2, 3]
print(list(combinations(nums, 2)))