Random String Generation and Analysis

  • Share this:

Code introduction


This function generates a random string, extracts letters and numbers from it, gets the current date, current working directory, script name, serializes a dictionary, and calculates the MD5 hash of a string.


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

Code Type : Function

Code Difficulty : Intermediate


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

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

def xxx(arg1, arg2, arg3):
    # 使用random生成一个随机字符串
    random_str = generate_random_string()
    # 使用string获取所有字母
    letters = string.ascii_letters
    # 使用re找到字符串中的所有数字
    numbers = re.findall(r'\d', random_str)
    # 使用datetime获取当前日期
    current_date = datetime.datetime.now().strftime('%Y-%m-%d')
    # 使用os获取当前工作目录
    current_dir = os.getcwd()
    # 使用sys获取当前运行的脚本名称
    script_name = sys.argv[0]
    # 使用json序列化一个简单的字典
    data = {
        'name': 'John Doe',
        'age': 30
    }
    json_data = json.dumps(data)
    # 使用hashlib生成字符串的MD5散列值
    md5_hash = hashlib.md5(random_str.encode()).hexdigest()
    return random_str, letters, numbers, current_date, current_dir, script_name, json_data, md5_hash