In your random_char
function, you don't use x
at all. Replace it with _
(it's conventional in python to use _
for throwaway variables). y
could also be renamed to something more descriptive. The name of the function could also be renamed to random_chars
since you're generating one or more of them.
Also, use string formatting instead of all those extra variables:
def generate_key():
return (f"{random.randrange(1, 9)}{random_chars(5)}{random.randrange(1, 9)}{random_chars(2)}"
f"{random.randrange(1, 9)}{random_chars(1)}{random.randrange(1, 9)}{random_chars(3)}")
Note that the f-strings are available for Python versions >= 3.6
As a side note, there's this nice exrex which can:
Generate all - or random - matching strings to a given regular
expression and more. It's pure python, without external dependencies.
Given some pattern (similar to what you want):
r"(\d[A-Z]{1,4}){4}"
(...){4}
matches the previous token exactly 4 times.
\d
matches a digit (equivalent to [0-9]
)
[A-Z]{1,4}
matches the previous token between 1 and 4 times, as many times as possible, giving back as needed (greedy)
A-Z
matches a single character in the range between A (index 65) and Z (index 90) (case sensitive)
Note: I'm not a regex expert so there might be an easier / more correct version of this.
I think you can use this regex which returns exactly the pattern you want: \d{1,2}[A-Z]{5}\d[A-Z]{2}\d[A-Z]{1}\d[A-Z]{3}
Your entire code could be rewritten as:
import exrex
random_key = exrex.getone(r'(\d[A-Z]{1,4}){4}')
print(random_key)
Which would generate:
'3C2BBV3NGKJ2XYJ'
For more information about regular expressions feel free to search on the internet to get familiar with them. For tests, I usually use regex101
1-2 digits + 5*random uppercased letters + ...
or it can be any random string? \$\endgroup\$