for i in range(num):
code = "".join(random.choices(
string.ascii_uppercase string.digits,
k = 16
))
file.write(f"{code}\n")
So this is a code I made which randomly generates 16 characters, I would like for the output to also be in different formats. These are all the formats:
XX-XXXX-XXXX-XXXX-XXXX -- [18 chars] Letters Numbers [All capital]
XXX XXX XXXX -- [10 chars] Only Numbers
XXXX XXXX XXXX -- [12 chars] Letters Numbers [All Capital]
XXXXXXXXXXXXXXXX -- [16 chars] Letters Numbers [All Capital]
I'd like it to do 1 of the 4 randomly [as well as the one I made] The problem I'm having is adding the "-"'s for the first one. It doesn't apply to the last two though, but for those ones there will be a space as indicated.
CodePudding user response:
Try this:
import random
from string import digits, ascii_uppercase
def get_random_template(filename: str, n: int) -> None:
"""Saves n randomly generated templates to filename."""
t1 = "{}{}-{}{}{}{}-{}{}{}{}-{}{}{}{}".format(*random.choices(ascii_uppercase digits, k=18))
t2 = "{}{}{} {}{}{} {}{}{}{}".format(*random.choices(digits, k=10))
t3 = "{}{}{}{} {}{}{}{} {}{}{}{}".format(*random.choices(ascii_uppercase digits, k=12))
t4 = "{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}".format(*random.choices(ascii_uppercase digits, k=16))
for i in range(n):
random_template = random.choice([t1, t2, t3, t4])
# Write template(s) file:
with open(filename, 'a') as file_obj:
file_obj.write(random_template '\n')
print(f'Successfully saved {n} file(s) to {filename}.')
if __name__ == '__main__':
get_random_template('myTemplatefile.txt', 10)
CodePudding user response:
You could try this:
import random
import string
def rand_int_char(num: int) -> str:
return "".join(random.choices(string.ascii_letters.upper() string.digits, k=num))
def rand_int(num: int) -> str:
return "".join(random.choices(string.digits, k=num))
random_num = random.randint(1, 4)
if random_num == 1:
# Case 1 : XX-XXXX-XXXX-XXXX-XXXX
print(f"{rand_int_char(2)}-{rand_int_char(4)}-{rand_int_char(4)}-{rand_int_char(4)}-{rand_int_char(4)}")
elif random_num == 2:
# Case 2 : XXX XXX XXX
print(f"{rand_int(3)} {rand_int(3)} {rand_int(4)}")
elif random_num == 3:
# Case 3 : XXXX XXXX XXXX
print(f"{rand_int_char(4)} {rand_int_char(4)} {rand_int_char(4)}")
else:
# Case 4 : XXXXXXXXXXXXXXXX
print(rand_int_char(16))