LoginSignup
67

More than 3 years have passed since last update.

Pythonを使ってランダムな文字列を生成

Last updated at Posted at 2018-02-20
目的

文字数nを与えるとその長さのランダムな英数字の文字列を作成する.

環境
$ python
Python 3.6.2 |Anaconda custom (64-bit)| (default, Jul 20 2017, 13:14:59)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

(追記) Python 2.7.14でも動きました.

コード
import random, string

def randomname(n):
   randlst = [random.choice(string.ascii_letters + string.digits) for i in range(n)]
   return ''.join(randlst)
生成例
>>> randomname(10)
'hBJN0XntN6'
>>> randomname(10)
'7we4CMGjTj'
>>> randomname(8)
'JRBLZVEG'
>>> randomname(8)
'woccb8Vn'
追記

@tag1216 さんからの補足です.
ありがとうございました.

import random, string

def randomname(n):
   return ''.join(random.choices(string.ascii_letters + string.digits, k=n))

Python 3.6以降であれば上記で同じ処理が可能です.
(追記: コード間違ってたので修正および加筆しました)

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
67