pythonrandomlimitstring-lengthchr

Why can't I get more than 59 characters as output in this code?


I'm trying to create a code to train my python skills, it is a program that generates a random string with the alpha-num characters, by transforming them from the ASCII to characters, and then it will compare with the actual order of the normal alphabet and cryptograph the message by replacing the normal alphabet letters by the random alphabet letters in a random order following the index number of each one of these strings( the alphabet and the random generated alphabet). Here's the part I'm having problems: Generating the random alphabet

import random as r


# Here's the lower case
num_alfanumericos1 = [x for x in range(97,122)]
# Here's the upper case
num_alfanumericos2 = [x for x in range(65,90)]
# Here's the numbers
num_alfanumericos3 = [x for x in range(48,57)]

# I did it this way because I'll need to use the random.choice function that accepts int
numeros_alfanum = num_alfanumericos1 + num_alfanumericos2 + num_alfanumericos3
# Here's the actual order
alfanum='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
simbolos='!@#$%¨&*<>,.;:^~`´/+-'

rand_alfa=''
while len(rand_alfa)<62:
    escolha = r.choice(numeros_alfanum)
    escolha = chr(escolha)
    if rand_alfa.find(escolha)==-1:
        rand_alfa = rand_alfa + escolha
        
print(rand_alfa)

It isn't a simple alphabet, I included the lowcase, the uppercase and the numbers. The total length of the list is 62, but the code works only until I put 59 in the 'while' statement:

while len(rand_alfa)<59:

I don't know what it is happening, it simply don't run. I runned it on Spyder and Jupyter Notebook, but in the both the problem is the same. I noticed jupyter indicates an infinite loop with this code... But i'm not sure. Please, help me. haha


Solution

  • Your 3 initialized alphanumeric lists are populated incorrectly. Specifically, you're trying to populate them with these values:

    The problem is that the range(x,y) function is not inclusive of y. So, you're missing the final character of each. Instead, write:

    num_alfanumericos1 = [x for x in range(97,123)]
    num_alfanumericos2 = [x for x in range(65,91)]
    num_alfanumericos3 = [x for x in range(48,58)]
    

    Note: you can also convert a range to a list as follows:

    num_alfanumericos1 = list(range(97,123))