Print one character at a time on the same line in Python

avatar

Borislav Hadzhiev

Last updated: Sep 7, 2022

banner

Photo from Unsplash

Print one character at a time on the same line in Python #

To print one character at a time on the same line:

  1. Use a for loop to iterate over the string.
  2. Use the print() function to print each character.
  3. Set the end argument in the call to print() to an empty string.
main.py
my_str = 'bobbyhadz' for char in my_str: print(char, end='', flush=True) # 👉️ bobbyhadz # ---------------------------------------------------- for char in my_str: print(char, end=' ', flush=True) # 👉️ b o b b y h a d z

We used the end argument of the print function to print each character of a string on the same line.

The end argument is printed at the end of the message.

By default, end is set to a newline character (\n).

You can set the argument to an empty string to print the characters one at a time and without a separator.

main.py
my_str = 'bobbyhadz' for char in my_str: print(char, end='', flush=True) # 👉️ bobbyhadz

If you need to separate the characters with a space, set the end argument to a string containing a space.

main.py
my_str = 'bobbyhadz' for char in my_str: print(char, end=' ', flush=True) # 👉️ b o b b y h a d z

We set the flush argument of the print function to True to flush the stream each time a character is printed.

By default, the output of the print() function is buffered.

You can use the time.sleep() method if you need to print each character in the string with a delay.

main.py
import time my_str = 'bobbyhadz' for char in my_str: print(char, end='', flush=True) # 👉️ bobbyhadz time.sleep(0.33)

The time.sleep method takes a number that represents the seconds and suspends execution of the thread for the given number of seconds.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.