Print each word in a string in Python

avatar

Borislav Hadzhiev

Last updated: Sep 7, 2022

banner

Photo from Unsplash

Print each word in a string in Python #

To print each word in a string:

  1. Use the str.split() method to split the string on each space.
  2. Use a for loop to iterate over the list of words.
  3. Use the print() function to print each word.
main.py
my_str = 'bobby hadz .com' # ✅ print each word in string on separate lines for word in my_str.split(): # bobby # hadz # .com print(word) # ✅ print each word in string on the same line for word in my_str.split(): print(word, end='') # 👉️ bobbyhadz.com

We used the str.split() method to split the string into a list of words.

main.py
my_str = 'bobby hadz .com' print(my_str.split()) # 👉️ ['bobby', 'hadz', '.com']

The str.split() method splits the string into a list of substrings using a delimiter.

The method takes the following 2 parameters:

NameDescription
separatorSplit the string into substrings on each occurrence of the separator
maxsplitAt most maxsplit splits are done (optional)
When no separator is passed to the str.split() method, it splits the input string on one or more whitespace characters.

If the separator is not found in the string, a list containing only 1 element is returned.

The next step is to use a for loop to iterate over the list and print each word.

main.py
my_str = 'bobby hadz .com' for word in my_str.split(): # bobby # hadz # .com print(word)

If you need to print the words in the string on the same line, set the end argument in the call to print() to an empty string.

main.py
my_str = 'bobby hadz .com' for word in my_str.split(): print(word, end='') # 👉️ bobbyhadz.com

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

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

If you need to print the words in the string separated by a space, set the end argument to a space.

main.py
my_str = 'bobby hadz .com' for word in my_str.split(): print(word, end=' ') # 👉️ bobby hadz .com

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

main.py
import time my_str = 'bobby hadz .com' for word in my_str.split(): # bobby # hadz # .com print(word) time.sleep(0.66)

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.