Reputation: 53
I'm trying to write a program that will create a randomly generated eight-character key (in ASCII characters). So far I have been able to get the 8 different numbers, then convert them into their equivalent ASCII character:
> import random
> for i in range(0,8):
> key = random.randint(33,126)
> key = chr(key)
> print(key)
however when I run the program it prints (the output is at least always different):
> ~
> e
> E
> v
> k
> `
> (
> X
when ideally I would like it to print (with no spaces in-between):
> ~eEvk`(X
but I have tried so many methods (formatting included) to put it into a string but nothing has worked! Sorry for the lengthy question, but I hope it made sense. An answer ASAP would be really appreciated. Thank you!
Upvotes: 4
Views: 3685
Reputation: 5391
Following on what you have done, you can add it to a list and then print the list at the end of the loop
import random
l = []
for i in range(0,8):
key = random.randint(33,126)
key = chr(key)
l.append(key)
print("".join(l))
Upvotes: 2
Reputation: 1180
You can do something like this:
import random
print("".join(chr(random.randint(33,126)) for _ in range(8)))
Or use string module:
import random
import string
print("".join(random.choice(string.printable) for _ in range(8)))
Upvotes: 1
Reputation: 8561
You have a couple options for dealing with this.
First, if you want to print()
each character but don't want the newline, you can tell it to keep output on the same line like this:
import random
for i in range(0,8):
key = random.randint(33,126)
key = chr(key)
print(key, end='')
Another option would be to start with an empty string s = ''
and add each key to it as you make them, and then print the whole string at the end:
import random
s = ''
for i in range(0,8):
key = random.randint(33,126)
s += chr(key)
print(s)
Upvotes: 1