python生成随机数、随机字符、随机字符串


python生成随机数、随机字符、随机字符串

本文是基于Windows 10系统环境,实现python生成随机数、随机字符、随机字符串:


(1) 生成随机数

  • 随机整数
import random

num = random.randint(1, 50) # 闭区间
print(num)
  • 随机选取0到100间的偶数
import random

num = random.randrange(0, 101, 2) # 左闭右开区间
print(num)
  • 随机浮点数
import random

num = random.random() # 生成0-1之间的随机浮点数
num2 = random.uniform(1, 10) # 生成的随机浮点数归一化到区间1-10
print(num)
print(num2)

(2) 生成随机字符

  • 随机字符
import random

alphabet = 'abcdefghijklmnopqrstuvwxyz!@#$%^&*()'
char = random.choice(alphabet)
print(char)

(3) 生成随机字符串

  • 生成指定数量的随机字符串
import random

alphabet = 'abcdefghijklmnopqrstuvwxyz!@#$%^&*()'
characters = random.sample(alphabet, 5)
print(characters)
  • 从a-zA-Z0-9生成指定数量的随机字符
import random
import string

value = ''.join(random.sample(string.ascii_letters + string.digits, 8))
print(value)
  • 随机选取字符串
import random

table = ['剪刀', '石头', '布']
print(random.choice(table))

python生成随机数、随机字符、随机字符串介绍到这里,更多python学习请参考编程字典python教程和问答部分,谢谢大家对编程字典的支持。


原文链接:https://blog.csdn.net/qq_32599479/article/details/91042234?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522163141071916780271568398%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fnavwordall.%2522%257D&request_id=163141071916780271568398&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~navwordall~first_rank_ecpm_v1~rank_v29_ecpm-29-91042234.pc_search_insert_download&utm_term=python&spm=1018.2226.3001.4187