5

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!

3 Answers 3

2

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)) 
Sign up to request clarification or add additional context in comments.

2 Comments

Or just ''.join(chr(random.randint(33,126)) for _ in range(8))
That is even better indeed.
1

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)

Comments

1

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)))

1 Comment

string.printable is slightly different than range(33, 127) for instance it includes tabs, carriage returns, line feeds... etc...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.