Python 作 ▸ 2019-11-29 16:05 Python3.7 ランダムな文字列を生成 #Python string の定数と random.choice() / random.choices() を使う Python 3.7.4 string の組み込み定数で使えそうなのは以下 stringwhitespace = ' \t\n\r\v\f' ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz' ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' ascii_letters = ascii_lowercase + ascii_uppercase digits = '0123456789' hexdigits = digits + 'abcdef' + 'ABCDEF' octdigits = '01234567' punctuation = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~""" printable = digits + ascii_letters + punctuation + whitespace英数字 + 記号import string, random length = 32 chars = string.ascii_letters + string.digits + string.punctuation randl = random.choices(chars, k=length) randstr = ''.join(randl) print(randstr)実行結果 (5回)_Y+UJ@ya8Lvk~yDSzN:m+{lS><u|WI~u 3a=Zm*'[>?F:EFLA@sj|2nySNu?a}\iy CF93|k$j}-s)9Em=#B\PeE]jl15R"i^` f08r-&Ekn&tvs>Mh1x3{$rNz+J6d`j[B #$:*f)-"uQnfZ5m{6Jb.@jZ90`_I])V#先頭は英数字のみ、以後は英数字 + 記号import string, random length = 32 firstchars = string.ascii_letters + string.digits # 英数字のみ allchars = firstchars + string.punctuation # 英数字 + 記号 randl = [random.choice(firstchars)] + random.choices(allchars, k=length - 1) randstr = ''.join(randl) print(randstr)実行結果 (10回)H;3:60flh{8EYTIgS<C,uq'&uaV_RGHL 1=b7q\I\/?Vq}*p+O'0uR6Rd4>uPv|-5 TZH#a[j^:ETJAe@rThwxIe},k3a.8+^L W5r_y(-s797K#)F?p*Lg\b9-~F1PSj+X b8(Ay2(o#FPzo^|<q+0M[=clZ4|`ko$f zvQ<!O:SK^;LU`UI>Xj*~N<]*F6IZ4nC SBDh)H@4!GY$GGAu(>b}:xiQHeHuDGGQ D=3|OApGlaQY(D'LNq8rAx;hX}@?2^y| es'[1Q4W'v_]$M1@&P$x9&U7,b\&PJ#o O=bYll\B}8K)[x3^|jI6cXfY/gq=HgX9