Print one character at a time in a while loop in Python

avatar

Borislav Hadzhiev

Last updated: Sep 7, 2022

banner

Photo from Unsplash

Print one character at a time in a while loop in Python #

To print one character at a time in a while loop:

  1. Use a while loop to iterate len(string) - 1 times.
  2. Use the print() function to print each character.
  3. The while loop will stop iterating when the condition is no longer met.
main.py
my_str = 'bobbyhadz' index = 0 while index < len(my_str): # 👇️ print each character on separate line print(my_str[index]) # b # o # b # ... index += 1 # -------------------------- index = 0 while index < len(my_str): # 👇️ print characters on the same line print(my_str[index], end='') # 👉️ bobbyhadz index += 1

The first example uses a while loop to print the character in a string on separate lines.

The second example uses a while loop to print the characters on the same line.

We declared an index variable and initially set it to 0.

On each iteration, we increment the index by 1 until the condition of the while loop is no longer met.

main.py
my_str = 'bobbyhadz' index = 0 while index < len(my_str): # 👇️ print each character on separate line print(my_str[index]) index += 1

Once the index variable stores a value that is equal to the string's length, we break out of the loop.

You can use the end argument of the print() function to print the characters of the string on the same line.

main.py
index = 0 while index < len(my_str): # 👇️ print characters on the same line print(my_str[index], end='') # 👉️ bobbyhadz index += 1

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 a space if you need to print the characters of the string separated by spaces.

main.py
my_str = 'bobbyhadz' index = 0 while index < len(my_str): print(my_str[index], end=' ') # 👉️ b o b b y h a d z index += 1

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' index = 0 while index < len(my_str): print(my_str[index]) time.sleep(0.33) index += 1

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.