Python Generate Random String From [a-z0-9]


Generate a random string from [a-z0-9] in Python. Read the documentation of random module in Python Standard Library is enough for implementation. random.choice is exactly the function we need to randomly pick up letter from alphabet.

Run Code on repl.it

rdnstr.py | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import random

ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789"

def random_string(strlen):
  result = ""
  for i in range(strlen):
    result += random.choice(ALPHABET)

  return result


if __name__ == '__main__':
  # for test purpose
  random.seed()
  print(random_string(5))
  print(random_string(6))
  print(random_string(7))

Tested on:

  • Ubuntu 16.10
  • Python 2.7.12+ & 3.5.2+

References:

[1]
[2]
[3]
[4]