python编程

python基础--random模块&re模块

2017-12-29  本文已影响0人  Cassie测试路

random模块

import random

# 输出0-1之间的随机浮点数,x in the interval [0, 1)
random.random()           # 0.31655425988339436

# 返回a-b之间随机的整数,Return random integer in range [a, b]
random.randint(0, 10)     # 0    2    4   6   7  

# 随机输出a-b之间的浮点数, in the range [a, b) or [a, b]
random.uniform(0, 1)     # 0.6220953395446402
# 随机生成a-b之间的保留2位小数的浮点数
a = random.uniform(10, 20)
print round(a, 2)
# random.choice(),随机从列表/元组/字符串输出一个字符串
random.choice("abcdefghijklmnopqrstuvwxyz")      #  a    y    u

# random.sample(),随机从列表/元组/字符串取n个元素,返回list
random.sample("abcdefghijklmnopqrstuvwxyz", 3)               # ["a", "w", "f"]    ["d", "k", "l"]
"".join(random.sample("abcdefghijklmnopqrstuvwxyz", 3))   # awf    qwe   ert
# random.shuffle()对原列表元素进行随机打乱,返回None
a = [1, 2, 3, 4, 5]
b = random.shuffle(a)
print(a)     # [3, 5, 2, 1, 4]
print(b)     # None
phone = "1"+str(random.randint(3,8))+"".join(random.sample("0123456789", 9))  
print(phone)     # 13680352791

# 写法2
phone = "1"+str(random.randint(3, 8))+  ''.join(str(random.choice(range(10))) for x in range(9))

# 写法3
from faker import Faker
phone = Faker("zh_CN").phone_number()

re模块

e = re.match(r'www', "www.www.codemao.cn")        # <_sre.SRE_Match object; span=(0, 3), match='www'>
e.group(0)         # 'www'

e = re.match(r'w+', "www.www.codemao.cn")       # <_sre.SRE_Match object; span=(0, 3), match='www'>
上一篇 下一篇

猜你喜欢

热点阅读