Search code examples
pythonascii

Using ascii Characters by Import


So I am making a random name generator and I want to import ASCII instead of just writing out all of it. Is there any way I can import it into my code? I have tried doing the code below which doesn't do anything, please help

When I ran it, nothing happened, maybe I'm using it wrong? I have never tried importing it before

"".join(chr(x) for x in range(32,127))

`


Solution

  • Use string module:

    import string
    
    # You have to store the result in a variable to use it
    choices = ''.join([string.ascii_letters, string.digits, string.punctuation, ' '])
    
    print(choices)
    # Output
    'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ '
    

    To use it:

    import random
    
    # Select one character
    print(random.choice(choices))
    # Output
    ';'
    
    # Generate string
    print(''.join(random.choices(choices, k=16)))
    # Output
    Phhs5uYa]O^+]kJz
    

    For your information, choices is equivalent to your code (same characters):

    >>> set(choices).symmetric_difference("".join(chr(x) for x in range(32,127)))
    set()