Python 實現隨機打亂字串

寒爵發表於2018-09-19
from random import shuffle


def shuffle_str(s):
    # 將字串轉換成列表
    str_list = list(s)
    # 呼叫random模組的shuffle函式打亂列表
    shuffle(str_list)
    # 將列表轉字串
    return ``.join(str_list)


# 呼叫
if __name__ == `__main__`:
    for i in range(5):
        print(shuffle_str(`hello,world!`))

輸出結果:

!lrw,hloldeo
!doorwhelll,
w,rhlloe!dol
dlehl!lo,orw
whl,!oldrloe

 

相關文章