DEV Community

Zsolt Szakal
Zsolt Szakal

Posted on

Simplest Python Random Password - with only 6 lines of code

The most simple way to generate a random password in Python.

  1. import string
  2. import random
  3. with string create possible charachters
  4. with random generate a random number
  5. create password
  6. print password to the console
import string
import random

password_chars = string.ascii_letters + string.digits + string.punctuation
length = random.randint(12, 15)

password = "".join([random.choice(password_chars) for _ in range(length)])

print(password)
Enter fullscreen mode Exit fullscreen mode

Or a single line password generator below:

import string
import random

print("".join([random.choice(string.ascii_letters + string.digits + string.punctuation) for _ in range(random.randint(12, 15))]))
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ
"".join(random.choices(string.ascii_letters + string.digits + string.punctuation, k=random.randint(12, 15)))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
hammertoe profile image
Matt Hamilton

This is what I love about stumbling upon random stuff like this. I've been a Python developer for two decades, and yet had no idea that random.choices (the plural) existed. Looks like it came in 3.6. Thanks!