【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


相关文章
|
7天前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
191 99
|
10天前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
10天前
|
开发者 Python
Python f-strings:更优雅的字符串格式化技巧
Python f-strings:更优雅的字符串格式化技巧
|
10天前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
21天前
|
Python
使用Python f-strings实现更优雅的字符串格式化
使用Python f-strings实现更优雅的字符串格式化
|
1月前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
209 92
|
7天前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
165 100
|
1月前
|
数据采集 存储 数据库
Python字符串全解析:从基础操作到高级技巧
Python字符串处理详解,涵盖基础操作、格式化、编码、正则表达式及性能优化等内容,结合实际案例帮助开发者系统掌握字符串核心技能,提升文本处理与编程效率。
162 0
|
1月前
|
存储 小程序 索引
Python变量与基础数据类型:整型、浮点型和字符串操作全解析
在Python编程中,变量和数据类型是构建程序的基础。本文介绍了三种基本数据类型:整型(int)、浮点型(float)和字符串(str),以及它们在变量中的使用方式和常见操作。通过理解变量的动态特性、数据类型的转换与运算规则,初学者可以更高效地编写清晰、简洁的Python代码,为后续学习打下坚实基础。
330 0

推荐镜像

更多