How to generate different license plates and save them to a file?

Viewed 682

I'm making a python program that generates Spanish license plates, and I want the program to ask you how many license plates you want (saved on the 'quantity' variable), then generate that many.

I also want to know if it's possible to save the output to a file.

Thanks in advance!

import random
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
nums = '0123456789'
letters = ''
numbers = ''
quantity = int(input('Cuántas matrículas quieres? '))
for c in range(3):
    letters += random.choice(chars)
    
for c in range(4):
    numbers += random.choice(nums)

print('Tu matrícula es', numbers, letters)
4 Answers

You can use list comprehension:

for i in range(quantity):
    print('Tu matrícula es', ''.join([random.choice(chars) for i in range(3)]+[random.choice(nums) for i in range(4)]))

example output for quantity = 3:

Tu matrícula es OBR8830
Tu matrícula es VXW4958
Tu matrícula es PWU6749

UPDATE: If you need a space between letters and numbers:

for i in range(quantity):
  print('Tu matrícula es', ''.join([random.choice(chars) for i in range(3)]+[' ']+[random.choice(nums) for i in range(4)]))

sample output:

Tu matrícula es GHT 3077
Tu matrícula es EQJ 3065
Tu matrícula es FQI 1923

In python you can do:

>>> 5 * "tT"
'tTtTtTtTtT'

So for your example:

output = quantity * (numbers + letters)
print(output)

And for writing to file:

with open('result.txt', 'w') as file:
    file.write(str(output))

You could have the logic to generate a license plate in a function, and then loop over and call it:

import random
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
nums = '0123456789'
quantity = int(input('Cuántas matrículas quieres? '))

def create_plate():
    letters = ''
    numbers = ''
    for c in range(3):
        letters += random.choice(chars)
    
    for c in range(4):
        numbers += random.choice(nums)

    return numbers + ' ' + letters

for i in range(0, quantity):
    print('Tu matrícula es', create_plate())

Here we generate the desired amount of different Spanish plates, and save them to a file:

import random

def generate_spanish_plate():
    chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    nums = '0123456789'
    letters = ''
    numbers = ''
    for c in range(3):
        letters += random.choice(chars)
    for c in range(4):
        numbers += random.choice(nums)
    return f'{numbers} {letters}'

quantity = int(input('Cuántas matrículas quieres? '))

plates = []

for i in range(quantity):
    new_plate = generate_spanish_plate()
    # Verify plate is hasn't been generated
    while new_plate in plates:
        new_plate = generate_spanish_plate()
    plates.append(new_plate)

# Save to file
with open('spanish_plates.txt', 'w') as file:
    file.write(str(plates))


Related