【python】生成随机数字/字母/指定位数的字母+数字的字符串

简介: 【python】生成随机数字/字母/指定位数的字母+数字的字符串

在利用python代码进行开发或者测试中,难免会遇到一些需要输入随机值的相关操作,这里特意总结了一下:

一、随机数字的生成

(1)生成0-9(或其他数字段)中的一个(串)随机数字

import random
def create_random_int_number():
    """随机返回从0-9之间的整数"""
    return random.randint(0, 9)
    #也可以根据续修返回其他长度的数字,这里我返回1000-9999中的任意一个数字
    # return random.randint(1000, 9999)
print(create_random_int_number())

运行结果:8

(2)生成0-9999(或其他数字段)之间的任意一个浮点数

import random
def create_random_float_number():
    """随机返回从0-9999之间的浮点数"""
    return random.uniform(0, 9999)
print(create_random_float_number())

运行结果:9393.133900249248

(3)生成0-1之间的任意一个浮点数

import random
def create_random_0_1_number():
    """随机返回一个0-1之间的浮点数"""
    return random.random()
print(create_random_0_1_number())

运行结果:0.0803613273312489

(4)随机选择数组中任意一个或几个元素

import random
def create_random_samples_from_list():
    """随机从ls数组中选2个元素"""
    ls = ["aaa", 1, 'class', 'createrandomsamplesfromlist', 9990]
    print(random.choice(ls))
    return random.sample(ls, 2)
print(create_random_samples_from_list())

运行结果:[1, ‘aaa’]

二、随机大小写字母的生成

(1)随机生成一个大写或小写的英文字母

import random
def create_random_string():
    """随机生成一个大写或小写的英文字母"""
    return random.choice(string.ascii_letters)
print(create_random_string())

运行结果:G

(2)随机生成一串包含大写或小写的英文字母

import random
def create_random_strings():
    """随机生成一串包含大写或小写的英文字母"""
    return string.ascii_letters
print(create_random_strings())

运行结果:abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

三、随机指定位数的字符+数组混合的字符串

def create_string_number(n):
    """生成一串指定位数的字符+数组混合的字符串"""
    m = random.randint(1, n)
    a = "".join([str(random.randint(0, 9)) for _ in range(m)])
    b = "".join([random.choice(string.ascii_letters) for _ in range(n - m)])
    return ''.join(random.sample(list(a + b), n))
print(create_string_number(9))

运行结果:148k808S4

相关文章
|
2天前
|
索引 Python
python字符串(str)
【5月更文挑战第8天】
10 3
|
2天前
|
Python
【Python操作基础】——字符串
【Python操作基础】——字符串
|
2天前
|
Python
Python注意字符串和字节字面量
【5月更文挑战第7天】Python注意字符串和字节字面量
14 4
|
2天前
|
Python
Python字符串和字节不要混淆str.format()和bytes.format()
【5月更文挑战第6天】Python字符串和字节不要混淆str.format()和bytes.format()
8 1
|
2天前
|
Python
Python字符串和字节使用正确的编码/解码
【5月更文挑战第6天】Python字符串和字节使用正确的编码/解码
7 2
|
2天前
|
存储 Python
python字符串和字节明确数据类型
【5月更文挑战第6天】python字符串和字节明确数据类型
10 2
|
2天前
|
Python
Python避免在字符串和字节之间混淆
【5月更文挑战第5天】Python避免在字符串和字节之间混淆
17 3
|
2天前
|
数据安全/隐私保护 开发者 Python
【Python 基础】检查字符串是否只包含数字和字母?
【5月更文挑战第8天】【Python 基础】检查字符串是否只包含数字和字母?
|
2天前
|
Python
【Python 基础】如何将一个字符串转化为全大写和全小写?
【5月更文挑战第8天】【Python 基础】如何将一个字符串转化为全大写和全小写?
|
2天前
|
Python
python学习-函数模块,数据结构,字符串和列表(下)
python学习-函数模块,数据结构,字符串和列表
73 0