Python Utility Functions Overview

  • Share this:

Code introduction


This set of code snippets uses multiple features from Python's built-in libraries, including generating random strings, calculating hashes, getting file size, system time, regular expression matching, factorial calculation, and sorting a list by length.


Technology Stack : random, json, os, sys, datetime, re, math, hashlib

Code Type : Code combination

Code Difficulty : Intermediate


                
                    
import random
import json
import os
import sys
import datetime
import re
import math
import hashlib

def generate_random_string(length):
    return ''.join(random.choices('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=length))

def calculate_hash(data, algorithm='sha256'):
    return hashlib.new(algorithm, data.encode('utf-8')).hexdigest()

def get_file_size(file_path):
    return os.path.getsize(file_path)

def get_system_time():
    return datetime.datetime.now()

def find_all_matches(text, pattern):
    return re.findall(pattern, text)

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

def sort_list_by_length(lst):
    return sorted(lst, key=len)