Python Utility Functions for Random String, JSON Conversion, Time, Pattern Matching, and Hashing

  • Share this:

Code introduction


This function defines a series of small functionalities, including generating a random string, converting to JSON, getting the current time, checking if a string contains a specific pattern, getting the path of the current script, and calculating the hash of a string.


Technology Stack : random, json, time, re, sys, os, hashlib

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
import json
import time
import re
import sys
import os
import hashlib

def xxx(arg1, arg2):
    # Generate a random string with a specific length
    def random_string(length):
        letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
        return ''.join(random.choice(letters) for i in range(length))

    # Convert a string to JSON format
    def string_to_json(string):
        return json.dumps(string)

    # Get the current time in milliseconds
    def get_current_time():
        return int(time.time() * 1000)

    # Check if a string contains a pattern
    def contains_pattern(string, pattern):
        return re.search(pattern, string) is not None

    # Get the path of the current script
    def get_script_path():
        return os.path.abspath(sys.argv[0])

    # Calculate the hash of a string
    def calculate_hash(string):
        return hashlib.sha256(string.encode()).hexdigest()

    # Example usage of the functions
    random_str = random_string(10)
    json_str = string_to_json({"name": "Example", "age": 30})
    current_time = get_current_time()
    contains_pattern_str = contains_pattern(random_str, r'[A-Z]')
    script_path = get_script_path()
    hash_str = calculate_hash(random_str)

    return {
        "random_string": random_str,
        "json_string": json_str,
        "current_time": current_time,
        "contains_pattern": contains_pattern_str,
        "script_path": script_path,
        "hash": hash_str
    }