Random String Generation and Analysis

  • Share this:

Code introduction


This function first generates a random string of a specified length, then retrieves the current time and current directory, converts the string to JSON format, calculates its MD5 hash, checks if it contains a digit, and finally calculates the length of the string and prints all results.


Technology Stack : string, random, datetime, os, json, hashlib, re

Code Type : Code function

Code Difficulty : Intermediate


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

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

def xxx(arg1, arg2):
    # 生成随机字符串
    random_string = generate_random_string(arg1)
    
    # 获取当前时间
    current_time = datetime.datetime.now()
    
    # 获取当前目录
    current_directory = os.getcwd()
    
    # 将字符串转换为JSON格式
    json_string = json.dumps({"random_string": random_string})
    
    # 计算字符串的MD5值
    md5_hash = hashlib.md5(random_string.encode()).hexdigest()
    
    # 检查字符串是否包含数字
    if re.search(r'\d', random_string):
        contains_digit = True
    else:
        contains_digit = False
    
    # 计算字符串的长度
    string_length = len(random_string)
    
    # 打印结果
    print(f"Random String: {random_string}")
    print(f"Current Time: {current_time}")
    print(f"Current Directory: {current_directory}")
    print(f"JSON String: {json_string}")
    print(f"MD5 Hash: {md5_hash}")
    print(f"Contains Digit: {contains_digit}")
    print(f"String Length: {string_length}")