How to Print Each Word in a String in Python?

Estimated read time 2 min read

To print each word in a string in Python, you can use the split() method to split the string into a list of words, and then use a for loop to iterate over the list and print each word. Here’s an example:

my_string = "Hello, World! This is a test."

words = my_string.split()

for word in words:
    print(word)

In this example, we define a string my_string. We then use the split() method to split the string into a list of words, which we store in the words variable. We then use a for loop to iterate over each word in the list, and we print each word using the print() function.

The split() method splits a string into a list of words by default, using whitespace (spaces, tabs, and newlines) as the separator. If you want to split the string using a different separator, you can pass that separator as an argument to the split() method, like this:

my_string = "Hello|World|This|is|a|test."

words = my_string.split('|')

for word in words:
    print(word)

This will split the string into a list of words using the | character as the separator, and print each word on a separate line.

Note that the split() method removes the separator characters from the string, so they won’t appear in the output. If you want to include the separator characters in the output, you’ll need to add them back in yourself. For example, you could modify the above code like this:

my_string = "Hello|World|This|is|a|test."

words = my_string.split('|')

for i, word in enumerate(words):
    if i < len(words) - 1:
        print(word + '|')
    else:
        print(word)

This will print each word followed by a | character, except for the last word, which is printed without the | character.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply