computing245
computing245

Reputation: 51

Choosing specific symbols to print in a random string

I am trying to print a random string which contains upper and lowercase letters, digits and symbols. This is my code:

genpassword = ''.join([random.choice(string.ascii_letters
                                     + string.digits
                                     + string.punctuation)
                       for n in range(12)])

So far it works. However, I want the program to only print specific symbols, which are the following:

symbols = ["!","$","%","^","&","*","(",")","-","_","=","+"]

The string.punctuation prints all these symbols but some others.

So how do I get my program to generate a string which contains only symbols from the list above?

Upvotes: 0

Views: 75

Answers (1)

bgse
bgse

Reputation: 8587

You can put all the characters you want into a string, and then use that instead of string.punctuation:

symbols = "!$%^&*()-_=+"
genpassword = ''.join([random.choice(string.ascii_letters + string.digits + symbols ) for n in range(12)])

This is actually how your code already works, for example string.ascii_letters is just a string as well, see in Python interpreter (a good way to experiment):

>>> import string
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

Upvotes: 1

Related Questions