python生成隨機數 隨機字串

2022-06-23 22:27:16 字數 1829 閱讀 3701

python生成隨機數、隨機字串

import random

import string

# 隨機整數:

print random.randint(1,50)

# 隨機選取0到100間的偶數:

print random.randrange(0, 101, 2)

# 隨機浮點數:

print random.random()

print random.uniform(1, 10)

# 隨機字元:

print random.choice('[email protected]#$%^&*()')

# 多個字元中生成指定數量的隨機字元:

print random.sample('zyxwvutsrqponmlkjihgfedcba',5)

# 從a-za-z0-9生成指定數量的隨機字元:

ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 8))

print ran_str

# 多個字元中選取指定數量的字元組成新字串:

prin ''.join(random.sample(['z','y','x','w','v','u','t','s','r','q','p','o','n','m','l','k','j','i','h','g','f','e','d','c','b','a'], 5))

# 隨機選取字串:

print random.choice(['剪刀', '石頭', '布'])

# 打亂排序

items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

print random.shuffle(items)

python生成隨機數、隨機字串

import random

import string

# 隨機整數:

print random.randint(1,50)

# 隨機選取0到100間的偶數:

print random.randrange(0, 101, 2)

# 隨機浮點數:

print random.random()

print random.uniform(1, 10)

# 隨機字元:

print random.choice('[email protected]#$%^&*()')

# 多個字元中生成指定數量的隨機字元:

print random.sample('zyxwvutsrqponmlkjihgfedcba',5)

# 從a-za-z0-9生成指定數量的隨機字元:

ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 8))

print ran_str

# 多個字元中選取指定數量的字元組成新字串:

prin ''.join(random.sample(['z','y','x','w','v','u','t','s','r','q','p','o','n','m','l','k','j','i','h','g','f','e','d','c','b','a'], 5))

# 隨機選取字串:

print random.choice(['剪刀', '石頭', '布'])

# 打亂排序

items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

print random.shuffle(items)