Created
January 21, 2026 14:23
-
-
Save ClimenteA/7ae34fe51e794414e5f8414975e368a0 to your computer and use it in GitHub Desktop.
Generates a URL-safe, 11-character string similar to YouTube video IDs.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import secrets | |
| import base64 | |
| def generate_youtube_id(): | |
| """ | |
| Generates a URL-safe, 11-character string similar to YouTube video IDs. | |
| Calculates 8 bytes of entropy (64 bits) and encodes it to Base64. | |
| """ | |
| # 1. Generate 8 random bytes (64 bits) | |
| random_bytes = secrets.token_bytes(8) | |
| # 2. Encode to URL-safe Base64 | |
| # urlsafe_b64encode replaces '+' with '-' and '/' with '_' | |
| base64_bytes = base64.urlsafe_b64encode(random_bytes) | |
| # 3. Convert bytes to string and remove the '==' padding | |
| # 8 bytes always results in 12 Base64 characters, with the last being padding. | |
| # YouTube IDs are the first 11 characters. | |
| video_id = base64_bytes.decode('utf-8').replace('=', '') | |
| return video_id | |
| # Example usage: | |
| print(generate_youtube_id()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment