Sitemap
Alishba Naveed

Alishba Naveed

Hello, I'm Alishba a passionate tech , explorer, and lifelong learner. Welcome to my Medium account.

Chapter 6: Python Standard Library

7 min readAug 16, 2023

--

  • Exploring the Built-in Modules
  • Date and Time Operations
  • Regular Expressions
Press enter or click to view image in full size

Exploring the Built-in Modules

Python, being a versatile programming language, comes with a rich standard library that includes a wide range of built-in modules. These modules offer various functionalities and tools that can greatly simplify development tasks. Here, I’ll provide an overview of some of the most commonly used built-in modules in Python:

  1. os: This module provides a way to interact with the operating system. It offers functions to manipulate files, directories, paths, and environment variables. Some common functions include os.path.join(), os.listdir(), and os.environ.

2. sys: The sys module provides access to system-specific parameters and functions. It's commonly used for interacting with the Python interpreter and managing command-line arguments. You can use sys.argv to access command-line arguments and sys.exit() to exit the program.

3 .datetime: This module is used for working with dates and times. It provides classes and functions for creating, formatting, and manipulating dates and times. The datetime.datetime class is commonly used for representing date and time information.

4.math: The math module provides mathematical functions and constants. It covers a wide range of operations such as trigonometric functions, logarithmic functions, and more advanced operations like factorial and exponential.

5 .random: The random module is used for generating random numbers. It includes functions for generating random integers, floats, and making random choices from sequences.

6.json: JSON (JavaScript Object Notation) is a common data format for exchanging data between a server and a client. The json module in Python provides functions for encoding Python objects into JSON strings and decoding JSON strings into Python objects.

7.re: The re module is used for working with regular expressions. Regular expressions are powerful tools for pattern matching and manipulation of strings. This module enables you to search, match, and replace strings based on patterns.

8.urllib: The urllib module allows you to work with URLs. It provides functions for opening URLs, reading data from them, and handling various URL-related tasks. The urllib.request submodule is often used for opening URLs.

9.collections: This module provides specialized data structures beyond the built-in types like lists and dictionaries. Notable classes include Counter for counting occurrences, deque for double-ended queues, and namedtuple for creating simple classes.

10.os.path: While part of the os module, os.path deserves a special mention. It provides functions for working with file paths in a platform-independent way. It's crucial for tasks involving file manipulation.

11. csv: The csv module is used for working with CSV (Comma-Separated Values) files. It provides classes for reading and writing CSV files, making it easy to handle tabular data.

12. sys: The sys module provides access to some variables used or maintained by the interpreter and functions that interact strongly with the interpreter. It's commonly used for managing command-line arguments, stdin/stdout, and more.

These are just a handful of the many built-in modules Python offers. Depending on your needs, you might also encounter and use other modules like time, socket, pickle, subprocess, and more. To explore the complete list of built-in modules and their functionalities, you can refer to the official Python documentation.

Date and Time Operations

Working with dates and times is a common task in programming, and Python provides the datetime module to handle various date and time operations. Here's an overview of how to perform date and time operations in Python:

  1. Importing the datetime Module: To start working with dates and times, you need to import the datetime module:
  • import datetime

2. Creating Dates and Times: The datetime module provides several classes for representing dates and times. The most commonly used classes are:

  • datetime.date: Represents a date (year, month, day).
  • datetime.time: Represents a time (hour, minute, second, microsecond).
  • datetime.datetime: Represents a combination of date and time.
  • datetime.timedelta: Represents a duration or difference between two dates/times.

3. Current Date and Time: You can obtain the current date and time using the datetime.datetime.now() function:

current_datetime = datetime.datetime.now() print(current_datetime)
  • current_datetime = datetime.datetime.now() print(current_datetime)

4.Creating Specific Dates and Times: You can create specific dates and times using the respective classes. For example:

specific_date = datetime.date(2023, 8, 16) specific_time = datetime.time(15, 30, 0) specific_datetime = datetime.datetime(2023, 8, 16, 15, 30, 0)
  • specific_date = datetime.date(2023, 8, 16) specific_time = datetime.time(15, 30, 0) specific_datetime = datetime.datetime(2023, 8, 16, 15, 30, 0)

5. Formatting and Parsing Dates and Times: You can format dates and times as strings using the strftime() method and parse strings into datetime objects using the strptime() function:

formatted_date = specific_date.strftime("%Y-%m-%d") parsed_datetime = datetime.datetime.strptime("2023-08-16 15:30:00", "%Y-%m-%d %H:%M:%S")
  • formatted_date = specific_date.strftime("%Y-%m-%d") parsed_datetime = datetime.datetime.strptime("2023-08-16 15:30:00", "%Y-%m-%d %H:%M:%S")

6. Date and Time Arithmetic: You can perform arithmetic operations on datetime objects and timedelta objects. For example:

time_difference = specific_datetime - current_datetime future_datetime = specific_datetime + datetime.timedelta(days=7)
  • time_difference = specific_datetime - current_datetime future_datetime = specific_datetime + datetime.timedelta(days=7)

7. Extracting Components: You can extract individual components (year, month, day, etc.) from datetime objects:

year = specific_date.year month = specific_date.month day = specific_date.day
  • year = specific_date.year month = specific_date.month day = specific_date.day

8. Comparing Dates and Times: You can compare datetime objects using comparison operators (<, >, <=, >=, ==, !=):

is_future = specific_datetime > current_datetime
  • is_future = specific_datetime > current_datetime

9. Time Zones: The datetime module does not natively handle time zones. For time zone support, you can use the pytz library or the built-in zoneinfo module in Python 3.9+.

Get Alishba Naveed’s stories in your inbox

Join Medium for free to get updates from this writer.

10. Formatting Directives: When using the strftime() method to format dates and times, you can use various formatting directives to represent different components. Some common ones include %Y for the year, %m for the month, %d for the day, %H for the hour, %M for the minute, and %S for the second.

These are some of the basic operations you can perform using the datetime module in Python. Depending on your specific use case, you may also need to work with time zones, handle daylight saving time, and perform more complex calculations involving dates and times.

Regular Expressions

Regular expressions (regex or regexp) are powerful tools for pattern matching and manipulation of strings. The re module in Python provides support for working with regular expressions. Regular expressions allow you to define search patterns using a combination of characters and special symbols. Here's an overview of working with regular expressions in Python:

  1. Importing the re Module: To use regular expressions in Python, you need to import the re module:
import re
  • import re

2. Basic Pattern Matching: The simplest regular expression is a literal string that matches itself. For example:

pattern = "apple" text = "I love apples." match = re.search(pattern, text) if match:     print("Match found:", match.group()) else:     print("No match")
  • pattern = "apple" text = "I love apples." match = re.search(pattern, text) if match: print("Match found:", match.group()) else: print("No match"

3 .Special Characters: Regular expressions use special characters to define more complex patterns:

  • .: Matches any character except a newline.
  • *: Matches zero or more occurrences of the preceding element.
  • +: Matches one or more occurrences of the preceding element.
  • ?: Matches zero or one occurrence of the preceding element.
  • \d: Matches any digit (0-9).
  • \w: Matches any word character (alphanumeric and underscore).
  • \s: Matches any whitespace character (space, tab, newline).
  • []: Defines a character set.
  • ^: Matches the start of a string.
  • $: Matches the end of a string.

4 . Quantifiers and Groups: You can use quantifiers to specify the number of occurrences of a pattern, and groups to group parts of a pattern:

pattern = r"ab+c" text = "abc abbcccc ac" matches = re.findall(pattern, text)
  • pattern = r"ab+c" text = "abc abbcccc ac" matches = re.findall(pattern, text)

5. Using Raw Strings: When defining regular expressions, it’s recommended to use raw strings (prefixing with r) to avoid unintended escape sequences:

pattern = r"\d{3}-\d{2}-\d{4}"
  • pattern = r"\d{3}-\d{2}-\d{4}"

6. Match Objects and Methods: The re.search() function returns a match object, which has several methods such as group() to retrieve the matched text. The re.findall() function returns a list of all matches.

7. Substitution: The re.sub() function is used to replace occurrences of a pattern with a specified string:

  • pattern = r"\d+" text = "I have 3 apples and 5 oranges." modified_text = re.sub(pattern, "X", text)
pattern = r"\d+" text = "I have 3 apples and 5 oranges." modified_text = re.sub(pattern, "X", text)

8. Flags: Flags modify the behavior of regular expression matching. Common flags include re.IGNORECASE for case-insensitive matching and re.MULTILINE for multiline matching.

pattern = r"apple" text = "I love Apples and apples." matches = re.findall(pattern, text, re.IGNORECASE)
  • pattern = r"apple" text = "I love Apples and apples." matches = re.findall(pattern, text, re.IGNORECASE)

9. Escaping Special Characters: If you want to match special characters as literal characters, you need to escape them using a backslash (\):

pattern = r"\." text = "This is a dot." matches = re.findall(pattern, text)
  • pattern = r"\." text = "This is a dot." matches = re.findall(pattern, text)

11. Lookahead and Lookbehind: These constructs allow you to specify conditions that must be satisfied ahead or behind a certain position in the string, without including them in the match itself.

pattern = r"\d+(?= dollars)"
text = "I have 50 dollars and 100 dollars."
matches = re.findall(pattern, text)

Regular expressions are a vast topic, and this overview covers only the basics. The Python re module provides a comprehensive set of functions and options for working with regular expressions. For more advanced usage, consult the official Python documentation and additional resources on regular expressions.

--

--

Alishba Naveed
Alishba Naveed

Hello, I'm Alishba a passionate tech , explorer, and lifelong learner. Welcome to my Medium account.