<article itemscope="itemscope" itemtype="http://schema.org/Article" class="article" data-v-66fed3b2="" data-v-6a3e47cf="" data-entry-id="6904899648130039816" data-draft-id="6904897298312986631">
本文是基于Windows 10系统环境,实现python生成随机数、随机字符、随机字符串:
(1) 生成随机数
-
随机整数
import random
num = random.randint(1, 50) # 闭区间 print(num) 1234
-
随机选取0到100间的偶数
import random
num = random.randrange(0, 101, 2) # 左闭右开区间 print(num) 1234
-
随机浮点数
import random
num = random.random() # 生成0-1之间的随机浮点数 num2 = random.uniform(1, 10) # 生成的随机浮点数归一化到区间1-10 print(num) print(num2) 123456
(2) 生成随机字符
-
随机字符
import random
alphabet = 'abcdefghijklmnopqrstuvwxyz!@#$%^&*()' char = random.choice(alphabet) print(char) 12345
(3) 生成随机字符串
-
生成指定数量的随机字符串
import random
alphabet = 'abcdefghijklmnopqrstuvwxyz!@#$%^&*()' characters = random.sample(alphabet, 5) print(characters) 12345
-
从a-zA-Z0-9生成指定数量的随机字符
import random import string
value = ''.join(random.sample(string.ascii_letters + string.digits, 8)) print(value) 12345
-
随机选取字符串
import random
table = ['剪刀', '石头', '布'] print(random.choice(table)) 1234
<style>.markdown-body pre,.markdown-body pre>code.hljs{color:#333;background:#f8f8f8}.hljs-comment,.hljs-quote{color:#998;font-style:italic}.hljs-keyword,.hljs-selector-tag,.hljs-subst{color:#333;font-weight:700}.hljs-literal,.hljs-number,.hljs-tag .hljs-attr,.hljs-template-variable,.hljs-variable{color:teal}.hljs-doctag,.hljs-string{color:#d14}.hljs-section,.hljs-selector-id,.hljs-title{color:#900;font-weight:700}.hljs-subst{font-weight:400}.hljs-class .hljs-title,.hljs-type{color:#458;font-weight:700}.hljs-attribute,.hljs-name,.hljs-tag{color:navy;font-weight:400}.hljs-link,.hljs-regexp{color:#009926}.hljs-bullet,.hljs-symbol{color:#990073}.hljs-built_in,.hljs-builtin-name{color:#0086b3}.hljs-meta{color:#999;font-weight:700}.hljs-deletion{background:#fdd}.hljs-addition{background:#dfd}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:700}</style>
</article>
点击666可白嫖领取
可加QQ:3271330538进行交流