Print each letter in a string on a new line in Python

avatar

Borislav Hadzhiev

Last updated: Sep 5, 2022

banner

Photo from Unsplash

Print each letter in a string on a new line in Python #

To print each letter in a string on a new line:

  1. Use a for loop to iterate over the string.
  2. Use the print() function to print each letter.
main.py
import time my_str = 'bhadz' # ✅ print each letter in string on a new line for letter in my_str: # b # h # a # d # z print(letter) # ------------------------------------- # ✅ print each letter in string on a new line with delay for letter in my_str: print(letter) time.sleep(0.33)

We used a for loop to iterate over a string and print each letter.

The print function takes one or more objects and prints them to sys.stdout.

The for loop prints each letter on a new line because the print() function adds a newline (\n) character at the end of each message.

main.py
print('a', 'b', 'c') # 👉️ 'a b c\n' print('a', 'b', 'c', end='') # 👉️ 'a b c'

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

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

main.py
my_str = 'bhadz' for letter in my_str: # b # h # a # d # z print(letter)

If you need to print each letter in the string with a delay, use the time.sleep() method.

main.py
import time my_str = 'bhadz' for letter in my_str: print(letter) 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.

An alternative to using a for loop is to use the str.join() method to join the characters in the string with a newline character separator.

main.py
my_str = 'bhadz' result = '\n'.join(my_str) # b # h # a # d # z print(result)

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

The string the method is called on is used as the separator between the elements.

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.