0% found this document useful (0 votes)
38 views11 pages

3.4 The Python Standard Library

The Python Standard Library is a collection of pre-installed modules and packages that offer a wide range of functionalities, including file I/O, string manipulation, and web development. It encompasses various categories such as string processing, data types, file access, and internet handling, providing essential tools for programming without needing external libraries. Key modules include 'os' for file operations, 'json' for data serialization, and 'unittest' for testing, among others.

Uploaded by

24pg204
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views11 pages

3.4 The Python Standard Library

The Python Standard Library is a collection of pre-installed modules and packages that offer a wide range of functionalities, including file I/O, string manipulation, and web development. It encompasses various categories such as string processing, data types, file access, and internet handling, providing essential tools for programming without needing external libraries. Key modules include 'os' for file operations, 'json' for data serialization, and 'unittest' for testing, among others.

Uploaded by

24pg204
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

The Python Standard Library

ThePythonStandardLibraryisacollectionofmodulesandpackagesthatcomepre-
installed
[Link],suchasfileI/O,stringmanipulatio
n, data handling, networking, web development, and much more. By leveraging
the standard library, you can solve many programming problems without needing
external libraries.

Categories of the Python Standard Library

Here’s an overview of the major categories and some commonly used modules
within them:

1. String and Text Processing

 string: Provides constants and classes for string operations.

python
Copycod
e
import string
print(string.ascii_lowercase) # abcdefghijklmnopqrstuvwxyz

 re: Regular expression matching and manipulation.

python
Copycod
e import
re
match=[Link](r"\d+","Order12345")
print([Link]()) # 12345

 textwrap: Formatting text into wrapped lines.

python
Copycod
e
import textwrap
print([Link]("This is a long piece of text.", width=10))

2. Data Types

 collections:Specialized container data types like deque, Counter, and


OrderedDict.

python
Copycod
e
from collections import Counter
print(Counter("mississippi")) # Counter({'i': 4, 's': 4, 'p': 2, 'm':
1})
 itertools: Efficient looping and combinatorial tools.

python
Copycod
e
from itertools import permutations
print(list(permutations("abc", 2))) # [('a', 'b'), ('a', 'c'), ...]

 array: Efficient arrays of basic values like integers or floats.

python
Copycod
e
from array import array
a = array('i', [1, 2, 3])
print(a[1]) # 2

3. File and Directory Access

 os: Interacting with the operating system, file paths, and environment
variables.

python
Copycod
e import
os
print([Link]()) # Current working directory

 shutil: High-level file operations like copying and moving files.

python
Copycod
e
import shutil
[Link]("[Link]", "[Link]")

 pathlib: Object-oriented file and path manipulation.

python
Copycod
e
from pathlib import Path
print([Link]()) # Current working directory

4. Data Serialization

 json: Parse and write JSON.

python
Copycod
e
import json
data={"name":"Alice","age":30} json_str
= [Link](data)
print(json_str) # {"name": "Alice", "age": 30}
 pickle: Serialize Python objects for storage or transmission.

python
Copycod
e
import pickle
data = {"key": "value"}
withopen("[Link]","wb")asf: [Link](data, f)

 csv: Read and write CSV files.

python
Copy
code
importcsv
withopen("[Link]","w",newline="")asf: writer
= [Link](f) [Link](["Name",
"Age"]) [Link](["Alice", 30])

5. Numeric and Mathematical Modules

 math:Mathematicalfunctionslikesqrt,sin,andconstantslike
pi. python
Copy code
importmath
print([Link]) # 3.141592653589793

 random: Generate random numbers and perform random selections.

python
Copycod
e
import random
print([Link](1, 10)) # Random number between 1 and 10

 statistics: Statistical operations like mean, median, and variance.

python
Copycod
e
import statistics
print([Link]([1, 2, 3, 4])) # 2.5

6. Internet and Web Handling

 urllib: Fetch data from URLs.

python
Copycod
e
import [Link]
response=[Link]("[Link]
print([Link]())

 http: Modules for HTTP handling.

python
Copycod
e
[Link],BaseHTTPRequestHandle
r # Set up a basic HTTP server

 socket: Low-level networking interface.

python
Copycod
e
import socket
print([Link]()) # Hostname of the machine

7. Date and Time

 datetime: Work with dates and times.

python
Copycod
e
from datetime import datetime
print([Link]()) #Currentdateandtime

 time: Time-related functions like delays or timestamps.

python
Copycod
e
import time
print([Link]()) # Current timestamp

 calendar: Work with calendars and dates.

python
Copycod
e
import calendar
print([Link](2024, 11)) # November 2024 calendar

8. System and OS Interface

 sys: System-specific parameters and functions.

python
Copy
code
importsys
print([Link]) # Python version
 subprocess: Run external commands and processes.

python
Copycod
e
import subprocess
[Link](["echo", "Hello, World!"])

 logging: Logging for applications.

python
Copycod
e
import logging
[Link](level=[Link])
[Link]("Thisisaninfomessage.")

9. Testing and Debugging

 unittest: Write unit tests for Python code.

python
Copycod
e
import unittest
classTestExample([Link]): def
test_addition(self):
[Link](2 + 2, 4)

 pdb: Debug Python code interactively.

python
Copy
code
importpdb
pdb.set_trace()

10. Concurrent Programming

 threading: Thread-based parallelism.


python
Copycod
e
importthreading
def worker():
print("Worker thread")
thread=[Link](target=worker)
[Link]()

 multiprocessing: Process-based parallelism.

python
Copycod
e
frommultiprocessingimportProcess def
worker():
print("Worker process")
process=Process(target=worker)
[Link]()

 asyncio: Asynchronous programming support.

python
Copycod
e
import asyncio
asyncdefmain():
print("Hello")
[Link](1)
print("World")
[Link](main())

You might also like