random模塊
import random
# 輸出0-1之間的隨機浮點數(shù),x in the interval [0, 1)
random.random() # 0.31655425988339436
# 返回a-b之間隨機的整數(shù),Return random integer in range [a, b]
random.randint(0, 10) # 0 2 4 6 7
# 隨機輸出a-b之間的浮點數(shù), in the range [a, b) or [a, b]
random.uniform(0, 1) # 0.6220953395446402
-
round(數(shù)值,精度)
,控制隨機數(shù)的精度
# 隨機生成a-b之間的保留2位小數(shù)的浮點數(shù)
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
- 隨機生成11位手機號:13********-18********
- range(10),表示[a, b),即0-9的數(shù)字
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模塊
-
re.match(pattern, string, flags=0)
,從起始位置判斷字符串是否匹配正則表達式,如果滿足返回正則表達式則馬海match對象,如果不滿足則返回None
-
re.search(pattern, string, flags=0)
,匹配成功re.search方法返回一個匹配的對象,否則返回None。
- re.match只匹配字符串的開始,如果字符串開始不符合正則表達式,則匹配失敗,函數(shù)返回None;而re.search匹配整個字符串,直到找到一個匹配。
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'>