'ASCII to String
I have this password generator:
from random import sample
character = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{}~'
print(''.join(sample(character, 10)))
Example output: bvwy2%-?/N
However, I don't like it that the variable character is so long.
I got the content of character from this ASCII table:

I used every character except |.
My question is how can I shorten the content of character?
Something like this:
for i in range(33, 126):
# get ASCII values ?
Solution 1:[1]
Since you know that your character values go from 33 to 126, you can create a string by
characters = "".join(chr(x) for x in range(33, 127))
As you noted, this contains a pipe. To remove this, simply use str.replace():
characters = characters.replace("|", "")
Which gives:
characters = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{}~'
However, since random.sample() can take any iterable, you could do the same thing with making characters a set. If you do this, you can have another set of disallowed characters and easily subtract the disallowed set from the all_chars set to get the allowed_chars set. For example, if you wanted to disallow pipes and quotes, you could do:
all_chars = set(chr(x) for x in range(33, 127))
disallowed_chars = {'|', "'", '"'}
allowed_chars = all_chars - disallowed_chars
random.sample(allowed_chars, 10) # This also works
Solution 2:[2]
Like @9769953 told it your code could be:
from random import sample
import string
character = string.ascii_letters + string.digits + string.punctuation
character.replace('|', '') # remove the |
print(''.join(sample(character, 10)))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pranav Hosangadi |
| Solution 2 | HRD |
