You can download this code by clicking the button below.
This code is now available for download.
Generate a random string of a specified length, which can be letters.
Technology Stack : random, string
Code Type : Custom function
Code Difficulty : Intermediate
import random
import string
import time
import re
import math
import sys
import os
import subprocess
def generate_random_string(length=10):
"""
生成一个指定长度的随机字符串。
:param length: 字符串的长度,默认为10
:return: 随机字符串
"""
if not isinstance(length, int) or length < 1:
raise ValueError("Length must be a positive integer.")
letters = string.ascii_letters
return ''.join(random.choice(letters) for i in range(length))
def get_current_time_formatted():
"""
获取当前时间并格式化为字符串。
:return: 格式化的当前时间字符串
"""
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
def find_all_occurrences(text, search):
"""
查找字符串中所有出现的子字符串。
:param text: 要搜索的文本
:param search: 要查找的子字符串
:return: 包含所有匹配项的列表
"""
return [m.start() for m in re.finditer(re.escape(search), text)]
def calculate_square_root(number):
"""
计算一个数的平方根。
:param number: 要计算平方根的数
:return: 平方根
"""
if number < 0:
raise ValueError("Cannot calculate square root of a negative number.")
return math.sqrt(number)
def run_system_command(command):
"""
运行系统命令。
:param command: 要运行的命令
:return: 命令的输出
"""
try:
result = subprocess.run(command, check=True, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
return result.stdout
except subprocess.CalledProcessError as e:
sys.exit(e.stderr)
def check_directory_exists(path):
"""
检查目录是否存在。
:param path: 要检查的目录路径
:return: 目录是否存在
"""
return os.path.isdir(path)
def json.dumps(data):
"""
将Python对象序列化为JSON字符串。
:param data: 要序列化的Python对象
:return: JSON字符串
"""
import json
return json.dumps(data)