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)
相关推荐
蓝莓味柯基35 分钟前
Python3:文件操作
python
xiaoh_71 小时前
解决视频处理中的 HEVC 解码错误:Could not find ref with POC xxx【已解决】
python·ffmpeg·音视频
明月与玄武2 小时前
Python编程的真谛:超越语法,理解编程本质
python·编程语言
CodeCraft Studio2 小时前
Excel处理控件Aspose.Cells教程:使用 Python 在 Excel 中进行数据验
开发语言·python·excel
拾忆-eleven2 小时前
C语言实战:用Pygame打造高难度水果消消乐游戏
c语言·python·pygame
旦莫3 小时前
Python 教程:我们可以给 Python 文件起中文名吗?
开发语言·python
豌豆花下猫3 小时前
Python 潮流周刊#99:如何在生产环境中运行 Python?(摘要)
后端·python·ai
小杨4043 小时前
python入门系列二十(peewee)
人工智能·python·pycharm
弧襪3 小时前
FlaskRestfulAPI接口的初步认识
python·flaskrestfulapi
船长@Quant3 小时前
文档构建:Sphinx全面使用指南 — 进阶篇
python·markdown·sphinx·文档构建