Python Utility Functions Collection

  • Share this:

Code introduction


This code collection contains multiple functions written using Python's built-in libraries, covering file operations, string processing, list operations, and mathematical calculations among other aspects.


Technology Stack : os, random, string

Code Type : Code collection

Code Difficulty : Intermediate


                
                    
import os
import random
import string

def generate_random_string(length=10):
    return ''.join(random.choice(string.ascii_lowercase) for _ in range(length))

def list_directory_content(path='.'):
    return os.listdir(path)

def count_vowels_in_string(input_string):
    return sum(1 for char in input_string.lower() if char in 'aeiou')

def zip_multiple_lists(*lists):
    return zip(*lists)

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

def check_palindrome(word):
    return word == word[::-1]

def calculate_hamming_distance(s1, s2):
    return sum(el1 != el2 for el1, el2 in zip(s1, s2))

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

def reverse_string(input_string):
    return input_string[::-1]

def generate_random_password(length=12):
    return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))

def read_first_line_from_file(file_path):
    with open(file_path, 'r') as file:
        return file.readline().strip()

def create_directory(path):
    os.makedirs(path, exist_ok=True)

def read_last_n_lines_from_file(file_path, n=5):
    with open(file_path, 'r') as file:
        lines = file.readlines()
        return lines[-n:]                
              
Tags: