Search code examples
python-3.xstringrandomalphanumeric

Specific string generation in python of 5 alphabets followed by 4 numbers. example ABCDE1234


I have used the following code but not getting the desired output. please help me.

"{}{}{}".format((random.choices(string.ascii_uppercase)for i in range(5)), random.randint(1000,9999))


Solution

  • I don't know exactly why it doesn't work, but I managed to get it to print the desired result using this code:

    x = []
    y = ""
    for i in range(5):
        x += random.choices(string.ascii_uppercase)
    
    x += str(random.randint(1000,9999))
        
    
    print (y.join(x))
    

    My guess is that it's because you're trying to add a list (your method of string generation produces a list of string characters) and an integer (randint produces an integer) to a string.