python生成随机字符串

随机字符的场景大致有以下场景:

1.产生随机字符串 无数字

2.产生随机长度的字符串 无数字、有数字

3.产生随机手机号

4.产生随机n位的数字

5.产生随机n以内的数字

随机使用的两种思路如下:

一:使用random.randint(0,n)

我们有一个包含多个字符的数组(或称为数据源数组),想要生成一个特定长度的字符串。为了实现这一点,我们将编写一个程序,它会根据所需的字符串长度执行相应次数的循环。在每次循环中,程序会调用random.randint(0, n-1)函数来生成一个随机数,其中n是数据源数组的长度。这个随机数将被用作索引,从数据源数组中选择一个字符。然后,程序会将选出的字符添加到结果字符串中。循环结束后,程序将返回这个由随机字符拼接而成的字符串。

python 复制代码
def generate_random_str(randomlength=16):
  """
  生成一个指定长度的随机字符串
  """
  random_str =''
  base_str ='ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
  length =len(base_str) -1
  for i in range(randomlength):
    random_str +=base_str[random.randint(0, length)]
  return random_str
if __name__ == '__main__':
  print(generate_random_str(15))
二:使用random.choice来随机选择元素,如果需要生成一个长度为n的字符串,我们可以从给定的字符数据源中随机选择n次字符。

关于random.choice()的用法,该函数接受一个序列(如列表、元组或字符串)作为参数,并随机返回该序列中的一个元素。

以下是使用random.choice来实现所需功能的重新表述:

要生成一个由随机字符组成的字符串,其长度由变量n指定,我们可以从给定的字符数据源(比如一个包含所有可能字符的列表或字符串)中,使用random.choice()函数随机选择n个字符,并将这些字符连接起来。

例如,假设我们有一个字符列表作为数据源:

python 复制代码
import random  
  
# 假设的字符数据源  
characters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']  
  
# 需要的字符串长度  
n = 10  
  
# 使用列表推导式和random.choice生成随机字符串  
random_string = ''.join(random.choice(characters) for _ in range(n))  
  
# 打印生成的随机字符串  
print(random_string)
python 复制代码
def getRandom(randomlength=16):
  """
  生成一个指定长度的随机字符串
  """
  digits=0123456789
  ascii_letters=abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
  str_list =[random.choice(digits +ascii_letters) for i in range(randomlength)]
  random_str =''.join(str_list)
  return random_str

最后,使用了dict字典实现按照mode按使用场景生成不同的字符串

python 复制代码
def getRandomString(mode="mixDigitLetter", len=15):
    #按照不同模式生成随机字符串
    upperLetter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    lowerLetter = "abcdefghigklmnopqrstuvwxyz"
    digits="0123456789"
    wpecialCharacters = "!@#$%&_-.+="
    randomMap ={"digit":digits,"upper":upperLetter,"lower":lowerLetter,"mixDigitLetter":upperLetter+lowerLetter+digits,"mixLetter":upperLetter+lowerLetter,"mixDigitLetterCharcter":upperLetter+lowerLetter+digits+wpecialCharacters}
    return getRandom(randomMap[mode],len)
相关推荐
mortimer2 分钟前
pydub下音频处理:跨越wav格式的4GB限制这道坎
python·ffmpeg·numpy
Dxy123931021643 分钟前
Python合并两个PDF文件
python·pdf
OAFD.1 小时前
Matplotlib 入门到实战:从零开始学 Python 数据可视化
python·信息可视化·matplotlib
WSSWWWSSW1 小时前
Numpy科学计算与数据分析:Numpy广播机制入门与实践
python·数据挖掘·数据分析·numpy
q567315232 小时前
Rust爬虫与代理池技术解析
开发语言·爬虫·python·rust
Dxy12393102162 小时前
Python如何合并两个Excel文件
爬虫·python·excel
fsnine3 小时前
数字图像处理基础——opencv库(Python)
人工智能·python·opencv
Yc98014 小时前
解决:开启魔法后vscode pip命令不能安装中科大python镜像问题
vscode·python·pip
xunie5 小时前
2025-08-09通过授权码的方式给exe程序充值
python
瓦尔登湖5085 小时前
DAY 36 复习日
python