Loops and print

by: PyLORD, 6 years ago


Hey fellow programmers, I have a question about how to print output on the same line in a for loop in Python. Here is the code

import time
y = "This is a string and it is useful in Python."
def nice_print(y):
for x in range(len(y)):
time.sleep(0.5)
print(y[x])

nice_print(y)

This is the result.

T
h
i
s

i
s

a

s
t
r
i
n
g

a
n
d

i
t

i
s

u
s
e
f
u
l

i
n

P
y
t
h
o
n
.
[Finished in 23.0s]




You must be logged in to post. Please login or register an account.



From:
https://stackoverflow.com/questions/493386/how-to-print-without-newline-or-space

Note the change in the print function. (It's actually two single quotes with no space between them.)  Python automatically adds a newline character and you can override it with anything.


import time
y = "This is a string and it is useful in Python."
def nice_print(y):
for x in range(len(y)):
time.sleep(0.5)
print(y[x], end='')

nice_print(y)



-jdonnelly81 6 years ago
Last edited 6 years ago

You must be logged in to post. Please login or register an account.


Not tryna be needy here. But I kinda want the typing effect that the loop shows, Because  when I add the tab escape character, It instantly prints everything without showing the pauses between characters.

-PyLORD 6 years ago
Last edited 6 years ago

You must be logged in to post. Please login or register an account.


A built-in file object that is analogous to the interpreter's standard output stream in Python . Unlike print, sys.stdout.write() doesn't switch to a new line after one text is displayed. To achieve this one can employ a new line escape character(n) .

import sys
for item in ['a','b','c','d']:
  sys.stdout.write(item)

While using stdout , you need to convert the object to a string yourself (by calling "str", for example) and there is no newline character . The return value for sys.stdout.write() returns the no. of bytes written which also gets printed on the interactive interpret prompt for any expressions enter.

http://net-informations.com/python/pro/print.htm

-jefryarch 3 years ago

You must be logged in to post. Please login or register an account.