What are the most useful Python modules from the standard library?


The Python Standard Library is a collection of script modules that may be used by a Python program, making it unnecessary to rewrite frequently used commands and streamlining the development process. By "calling/importing" them at the start of a script, they can be used.

A module is a file that contains Python code; an ‘coding.py’ file would be a module with the name ‘coding’.We utilise modules to divide complicated programmes into smaller, more manageable pieces. Modules also allow for the reuse of code.

In the following example, a module called ‘coding’ contains a function called add() that we developed. The function receives two numbers as input and outputs their sum −

def add(b, c):
# Adding two numbers and returning the result
   add_result = b + c
   return add_result

This article briefs us about most useful Python modules from the standard library.

The datetime module

We can utilise the objects that the datetime module gives us to store information about dates and times −

  • To generate dates without a time component, use datetime.date.

  • For times that are not related to a certain date, use datetime.time.

  • For objects that have both a date and an hour, use datetime.datetime.

  • datetime.timedelta: When we subtract one datetime from another, the outcome is a timedelta object, which stores discrepancies between dates or datetimes.

  • Time zone changes are represented as offsets from UTC via datetime.timezone objects. Datetime.tzinfo, of which this class is a subclass, is not intended for usage directly.

Example

Following is an example of datetime module fo getting the current date and time −

import datetime datetime_obj = datetime.datetime.now() print(datetime_obj)

Output

Following is an output of the above code −

2022-08-02 11:54:17.401520

The math module

A set of mathematical functions can be found in the math module. Although they can be applied to floats or integers, their primary purpose is to be applied to floats, and they often return floats.

Use the cmath module in its place if you need to use mathematical operations on complex numbers.

There are several techniques and constants in the math module.Few of them are listed below −

Methods

There are several techniques and constants in the math module.

  • math.acos() gives a number's arc cosine value.

  • The function acosh() returns the math's inverse hyperbolic cosine.

  • A number is rounded to the nearest integer using math.ceil().

  • The number of distinct, non-repeating methods to select item k from item n is returned by math.comb().

  • math.copysign() produces a float that contains the first parameter's value and the second parameter's sign.

  • math.cosh() returns a number's hyperbolic cosine.

  • Angles are translated from radians to degrees using math.degrees().

Constants

  • math.e returns the value of Euler (2.7182...).

  • Return a positive floating-point infinity with math.inf.

  • Return a floating-point NaN (Not a Number) value is math.nan.

  • math.pi yields PI (3.1415...).

  • math.tau returns tau (6.2831...)

Example

Following is an example to get pi value using math module −

import math math.pi

Output

Following is an output of the above code −

>>> math.pi
3.141592653589793

The random module (Pseudo -random numbers)

When a set of numbers seems to be random in some way but isn't, we refer to it as pseudo-random. Although pseudo-random number sequences are produced by a predictable algorithm, they have enough characteristics of truly random sequences to be useful in a wide range of applications.

To create pseudo-random numbers and do a few other tasks that require randomness, we can utilise Python's random package.

Example

Following is an example to generate a random integer between the given integers

import random random.randint(401, 1262)

Output

Following is an output of the above code −

>>> random.randint(401, 1262)
493
>>> random.randint(401, 1262)
1043
>>> random.randint(401, 1262)
1037

The re module

In a programming language, a regular expression (RE) is a unique text string used to provide a search pattern. For extracting information from text, such as code, files, logs, spreadsheets, or even documents, it is incredibly helpful.

The re module provides a set of functions that let us look for matches in a string which are as follows −

  • findall provides a list of all matching results.

  • search - If there is a match anywhere in the string split, it returns a Match object.

  • split provides a list that includes the string split at each match sub.

  • sub replaces a string with one or more matches

Metacharacters

Characters with a specific meaning are called metacharacters. Few of them are listed below −

  • \ is used to indicate a specific sequence or to escape special characters.

  • . Any character apart from newlines.

  • ^ Begins with

  • $ Ends with

Special sequence

A special sequence has a specific meaning and consists of a \ and one of the characters in the few of the lists given below −

  • \A - If the provided characters appear at the start of the string, the function returns a match.

  • \d - returns a match if the string includes numbers (numbers from 0-9).

  • \S - When a white space character is NOT present in the string, a match is returned.

  • \Z - If the provided characters are at the end of the string, it returns a match.

Example

Following is an example to print a list of all the matches

import re line = "Python coding using re module on" l = re.findall("on", line) print(l)

Output

Following is an output of the above code −

['on', 'on']

The os module

Numerous operating system functions can be carried out automatically. The OS module in Python has functions for adding and deleting folders, retrieving their contents, changing the directory, locating the current directory, and more.

Example

Following is an example to get the current working directory −

import os os.getcwd()

Output

Following is an output of the above code

>>> os.getcwd()
'C:\Users\Lenovo\Desktop'

The io module

We can control file-related input and output activities with the help of the Python I/O module. The benefit of using the IO module is that we can enhance the capability to enable writing to the Unicode data, thanks to the classes and functions that are available.

Example

Following is an example to open a file in the binary format for reading −

import io f = io.open("information.txt", "rb") print(f.read())

Output

Following is an output of the above code −

b"This tutorial looks at various Python comparison techniques for two files.\r\nWe'll go over how to perform this typical work by using the available modules\r\nreading two files, and comparing them line by line."

The json module

JSON, which stands for JavaScript Object Notation, is a popular data format for online data exchange. For structuring data between a client and a server, JSON is the best format. The programming language JavaScript is comparable to this language's syntax. Data transmission between the client and the web server is JSON's primary goal.

Example

Following is an example to to convert to Python from json

import json # JSON a = '{ "Company":"TutorialsPoint", "year":2006, "location":"Hyderabad"}' # parsing x b = json.loads(a) # result print(b["year"])

Output

Following is an output of the above code

2006

The copy module

A group of operations known as the Copy Module are used to duplicate various list, object, array, etc. items. Both shallow and deep copies may be produced with it.

When making a shallow copy, a new object is created that contains the references to the original elements. Therefore, a shallow copy only replicates the reference to nested objects rather to actually creating a copy of the underlying objects.

Deep copies make new objects while adding copies of nested objects that were already present in the original parts.

Example

Following is an example for creating a copy using shallow copy

import copy x = [[5, 6, 7], [13, 14, 15], [56, 57, 58]] y = copy.copy(x) print("Old_list:", x) print("New_list:", y)

Output

Following is an output of the above code:

Old_list: [[5, 6, 7], [13, 14, 15], [56, 57, 58]]
New_list: [[5, 6, 7], [13, 14, 15], [56, 57, 58]]

Note: There are various more modules like multiprocessing and threading module, urllib module, http module, locale module, sqllite3 module etc.

Updated on: 14-Nov-2022

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements