1. 程式人生 > >Python 生成一段隨機字串的三種寫法

Python 生成一段隨機字串的三種寫法

方法1

s1=''.join(random.choice(string.ascii_letters + string.digits) for _ in range(10**7))

方法2

for _ in range(10**7):
    s2 += random.choice(string.ascii_letters + string.digits)

方法3

s3=''.join(random.choices(string.ascii_letters + string.digits, k=10**7))

執行時間對比

import time, random,
string time_s_1 = time.time() s1=''.join(random.choice(string.ascii_letters + string.digits) for _ in range(10**7)) time_e_1 = time.time() print('method 1:', str(time_e_1 - time_s_1)) s2='' time_s_2 = time.time() for _ in range(10**7): s2 += random.choice(string.ascii_letters + string.digits) time_e_2 =
time.time() print('method 2:', str(time_e_2 - time_s_2)) time_s_3 = time.time() s3=''.join(random.choices(string.ascii_letters + string.digits, k=10**7)) time_e_3 = time.time() print('method 3:', str(time_e_3 - time_s_3))

下面是輸出的執行時間:

method 1: 9.464683055877686
method 2: 18.667069911956787
method 3: 2.693830728530884

結論:系統內建函式random.choices速度最快