0

I am trying to create an eight-character key by generating 8 random numbers between 33 and 126, then convert each of the 8 numbers into an ASCII character. I have been able to do all that:

print('Eight-Character Key: ')    
for i in range(0,8):
            key = random.randint(33,126)
            key = chr(key)
            print(key,end='')

The output is:

Eight-Character Key: 
BAU78)E)

But ideally I would like it to be all on the same line:

Eight-Character Key: BAU78) E)
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Lizzie
  • 53
  • 1
  • 6

2 Answers2

2

The obvious solution as you know how to use the end parameter of the print() function:

print('Eight-Character Key: ', end='')
#                              ^^^^^^
#                         no end-of-line after that

for i in range(0,8):
        key = random.randint(33,126)
        key = chr(key)
        print(key, end='')

print()
# ^^^^^
# end of line

And for a more "pythonic" way of doing that:

passwd = (chr(random.randint(33,126)) for _ in range(8))
print('Eight-Character Key:', "".join(passwd))

Please note however, whatever is your way of doing, it is not very safe as Python does not have low level control over the memory. So the generated password might be accessible from memory dump (see here for a possible workaround). Beyond that, as the password is probably displayed on the console, there are potentially many copy on that password in the heap of the various process involved too.

Community
  • 1
  • 1
Sylvain Leroux
  • 50,096
  • 7
  • 103
  • 125
0

Put the end after the first print statement

print('Eight-Character Key: ',end='')    
for i in range(0,8):
            key = random.randint(33,126)
            key = chr(key)
            print(key,end='')

Other ways to do it - By appending the key to a string and then print

k = ''
for i in range(0,8):
            key = random.randint(33,126)
            k += chr(key) 
print('Eight-Character Key: ',k,end='') 
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140