本文是基於Windows 10系統環境,實現python生成隨機數、隨機字元、隨機字串:
1.Windows 10
2.PyCharm 2018.3.5 for Windows (exe)
3.python 3.6.8 Windows x86 executable installer
————————————————
(1) 生成隨機數隨機整數import randomnum = random.randint(1, 50) # 閉區間print(num)
隨機選取0到100間的偶數import randomnum = random.randrange(0, 101, 2) # 左閉右開區間print(num)
隨機浮點數
import randomnum = random.random() # 生成0-1之間的隨機浮點數num2 = random.uniform(1, 10) # 生成的隨機浮點數歸一化到區間1-10print(num)print(num2)
(2) 生成隨機字元隨機字元
import randomalphabet = 'abcdefghijklmnopqrstuvwxyz!@#$%^&*()'char = random.choice(alphabet)print(char)
(3) 生成隨機字串
生成指定數量的隨機字串
import randomalphabet = 'abcdefghijklmnopqrstuvwxyz!@#$%^&*()'characters = random.sample(alphabet, 5)print(characters)
從a-zA-Z0-9生成指定數量的隨機字元
import randomimport stringvalue = ''.join(random.sample(string.ascii_letters + string.digits, 8))print(value)
隨機選取字串import randomtable = ['剪刀', '石頭', '布']print(random.choice(table))
最新評論