Read a string one character at a time in Python

avatar

Borislav Hadzhiev

Last updated: Sep 7, 2022

banner

Photo from Unsplash

Read a string one character at a time in Python #

To read a string one character at a time:

  1. Use a for loop to iterate over the string.
  2. Use the print() function to read each character.
main.py
string = 'bobbyhadz' # ✅ read a string one character at a time (on separate lines) for char in string: # b # o # b # b # y # ... print(char) # ------------------------------------------- # ✅ read a string one character at a time (on the same line) for char in string: print(char, end='') # 👉️ bobbyhadz # ------------------------------------------- # ✅ split string into list of characters my_list = list(string) print(my_list) # 👉️ ['b', 'o', 'b', 'b', 'y', 'h', 'a', 'd', 'z']

We used a for loop to iterate over the string and used the print() function to print each character.

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

By default, the print() function adds a newline (\n) character after each message.

main.py
string = 'bobbyhadz' for char in string: # b # o # b # b # y # ... print(char)

If you need to print the characters on the same line, set the end argument of the print() function to an empty string.

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

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

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

You can set it to a space if you need to print the characters of the string separated by spaces.

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

If you need to split the string into a list of characters, use the list() class.

main.py
string = 'bobbyhadz' my_list = list(string) print(my_list) # 👉️ ['b', 'o', 'b', 'b', 'y', 'h', 'a', 'd', 'z']

The list class takes an iterable and returns a list object.

You can use the time.sleep() method if you need to read a string one character at a time with a delay.

main.py
import time string = 'bobbyhadz' for char in string: # b # o # b # b # y # ... print(char) time.sleep(0.5)

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.