0

In this program I am trying to print my code as "random letters here" instead of "r" "a" "n" "d" "o" "m" etc.

import random
import time

All = "abcdefghijklmnopqrstuvwxyz1234567890"
i = 0

while i < 6:
    time.sleep(1)
    print(All[random.randint(1,35)])
    i += 1
Synthx
  • 5
  • 3
  • 1
    Does this answer your question? [Print in one line dynamically](https://stackoverflow.com/questions/3249524/print-in-one-line-dynamically) – Mike Scotty Nov 01 '21 at 22:45
  • why the `time.sleep`? – rv.kvetch Nov 01 '21 at 22:48
  • I'm a bit confused why an intentional delay is there, but to answer your question you can include a `end=''` in the print statement to get the desired output. – rv.kvetch Nov 01 '21 at 22:49

4 Answers4

0

Here you go!

import random
import time

All = "abcdefghijklmnopqrstuvwxyz1234567890"
i = 0
s = ""
while i < 6:
    time.sleep(1)
    s += All[random.randint(1,35)]
    i += 1

print(s)

Every print statements ends with a newline, so you need to "build" you string first (s in this case) first, then print it once.

Melvin
  • 33
  • 5
  • 1
    I think the idea of that `sleep` is to print in the same line but every second, not printing the entire result on one line – Alexandru DuDu Nov 01 '21 at 22:49
0

Try this.

import random
import time
import sys

All = "abcdefghijklmnopqrstuvwxyz1234567890"
i = 0
someString = ""
while i < 6:
    time.sleep(1)
    print()
    sys.stdout.write("\r "+str(All[random.randint(1,35)]))
    sys.stdout.flush()
    i += 1

Alexandru DuDu
  • 998
  • 1
  • 7
  • 19
0

I'm unsure if this is a homework project/question but if it isn't I guess you could just jumble them up using random.sample (I will un-iclude the sleep as there seems to be no need for it nor did you explain it's reasoning):

from random import sample

s = "abcdefghijklmnopqrstuvwxyz1234567890"
print(*sample(s, k=len(s)), sep='')

Sample result:

urftloqb38swz1ma9x5yg4p2ceijdhnk07v6

Also just fyi, the string you are using can be made pragmatically using the string library:

>>> import string
>>> string.ascii_lowercase + string.digits
abcdefghijklmnopqrstuvwxyz0123456789

It does have the 0 before the 1 instead of at the end but considering what you're doing it shouldn't make any meaningful difference.

Jab
  • 26,853
  • 21
  • 75
  • 114
0

You can pass end='' to the print statement so that subsequent prints are not separated by a newline, which is the default behavior. Also, here it makes sense to use a range iterator with for instead of while.

Note: I've taken the liberty to cut the sleep time in half, so it's easier to test it out.

import random
import time

All = "abcdefghijklmnopqrstuvwxyz1234567890"

for _ in range(6):
    time.sleep(0.5)
    print(All[random.randint(1, 35)], end='')
rv.kvetch
  • 9,940
  • 3
  • 24
  • 53