DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk4 min

How to Generate a Random String in Python

Use random.choice for non-security sample strings and secrets.choice for exact-length secrets. Learn when Python's URL-safe and hexadecimal token helpers fit better.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For ordinary sample text, build a string by repeatedly choosing from an alphabet with random.choice(). For passwords, authentication values, or other secrets, use secrets.choice() instead; Python documents random as unsuitable for cryptographic purposes.

Generate a random alphanumeric string

This creates a 16-character string containing uppercase letters, lowercase letters, and digits:

import random
import string

alphabet = string.ascii_letters + string.digits
value = ''.join(random.choice(alphabet) for _ in range(16))
print(value)

string.ascii_letters contains the ASCII lowercase and uppercase letters, while string.digits contains the digits 0 through 9. Change 16 to set the output length, or change alphabet to control which characters may appear. For example, use string.ascii_lowercase for lowercase letters only.

This method is appropriate for simulations and sample data when cryptographic unpredictability is not required. Python’s random documentation describes its generator as deterministic and unsuitable for cryptographic purposes. Do not use this snippet to create passwords, reset links, API keys, or session tokens.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Generate a secure string with a custom alphabet

When the character set and exact character count both matter for a secret, use secrets.choice():

import secrets
import string

alphabet = string.ascii_letters + string.digits
value = ''.join(secrets.choice(alphabet) for _ in range(16))
print(value)

This produces exactly 16 characters, each selected from the specified alphabet. To allow punctuation too, append an appropriate set of punctuation characters to alphabet. Avoid including characters your application cannot safely accept, and ensure the alphabet is not empty: choosing from an empty sequence raises an error.

Python’s secrets documentation recommends this module for security-sensitive values such as passwords and authentication tokens. The random module also has randbytes(), but Python explicitly directs readers to secrets for security tokens rather than using random.

Choose a token helper when encoded output is acceptable

If you need a URL-safe token and do not require a specific character count, use secrets.token_urlsafe():

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import secrets

token = secrets.token_urlsafe(32)
print(token)

The argument is the number of random bytes, not the number of output characters. The bytes are Base64-encoded into URL-safe text, which averages about 1.3 characters per input byte; therefore, use repeated secrets.choice() when the exact output length and alphabet are requirements.

For hexadecimal output, use secrets.token_hex(nbytes). Each random byte is represented by two hexadecimal characters, so secrets.token_hex(16) produces 32 hex characters. These helpers are convenient when their encodings fit the job; they are not interchangeable with a fixed-length string from an arbitrary alphabet.

Generate a password with required character classes

If a password policy requires certain classes, a secure approach is to generate candidates with secrets until one satisfies the policy. Python’s documentation illustrates this rejection-sampling pattern with a 10-character candidate containing at least one lowercase letter, one uppercase letter, and three digits:

import secrets
import string

alphabet = string.ascii_letters + string.digits

while True:
    password = ''.join(secrets.choice(alphabet) for _ in range(10))
    if (any(c.islower() for c in password)
            and any(c.isupper() for c in password)
            and sum(c.isdigit() for c in password) >= 3):
        break

print(password)

For more complex policies, another option is to securely choose at least one character from each required class, fill the remaining positions from the combined alphabet, and securely shuffle the result. That construction makes the requirements explicit, but the final shuffle must also use a security-oriented source such as secrets.SystemRandom().shuffle(), not random.shuffle().

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Generating a password does not determine how to store it. Python’s secrets guidance says applications should store passwords using a salted, strong one-way hash rather than in recoverable form.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Pick the method that matches the output

Need Use Important distinction
Sample data or simulations random.choice(alphabet), repeated and joined Convenient, but not for secrets.
Secret using a chosen alphabet and exact length secrets.choice(alphabet), repeated and joined Preserves the alphabet and exact character count.
URL-safe token without an exact character count secrets.token_urlsafe(nbytes) Argument specifies random bytes; encoded text length is approximate.
Hexadecimal token secrets.token_hex(nbytes) Each byte becomes two hexadecimal characters.

Troubleshoot common problems

  • The result is the wrong length: In the repeated-choice examples, the loop’s range() value is the exact character count. For token_urlsafe(), the argument is bytes, so the encoded result is not an exact character count.
  • Some characters are missing: Check the contents of alphabet. A generator can only choose characters included there; use string.ascii_letters, string.digits, or a custom string appropriate to the requirement.
  • Choosing from the alphabet raises an error: Make sure the alphabet is not empty. An empty sequence has no valid character to choose.
  • The output must be secure: Replace random.choice() with secrets.choice(). Do not use Python’s deterministic random generator for credentials or tokens.
  • A password policy needs several character classes: Check the generated candidate against each rule and retry, or construct required characters and securely shuffle them.

Performance and reliability considerations

Python’s cited documentation does not provide a performance benchmark comparing these methods, so choose based on the security requirement and output format rather than an assumed speed difference. For ordinary test data, random.choice() is simple; for a secret, the relevant distinction is that secrets is designed for security-sensitive randomness.

The secrets documentation has historically described 32 bytes (256 bits) as sufficient for typical use as of 2015, while noting that appropriate entropy can change as computers improve and that helper defaults may change. Treat that as a dated guidance statement, not a universal guarantee for every application. Set token sizes based on your system’s security requirements.

Or skip the browser setup

This Python task does not require a browser or screenshot API. If you also need website captures in a developer workflow, ScreenshotNeo provides a screenshot API and MCP server. Its one-request API example is:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import requests

r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

See the ScreenshotNeo API documentation for request options. It removes cookie banners, popups, and chat widgets before capture; bot checks, blank pages, and failed loads are not billed; an MCP server lets AI agents take screenshots; and the free plan includes 1,000 screenshots a month with no card, with paid plans starting at $5 for 3,000. Sign up for free.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.