How to Repeat a String Infinitely in Python



Python


In this article, we show how to repeat a string infinitely in Python.

Let's say you want to repeat the phrase, 'Game over', repeatedly.

How can we do this in Python?

So Python has a module called intertools that has a function called the cycle() function, which allows us to create an infinite loop. This can be of any data type such as an integer, a double, a string, etc.

In order to repeat a string infinitely, you must create a list and put that string within the last by itself so that it's the only element in that list.

So, again, in our code below, we will repeat the string, 'Game over', infinitely.



So the first thing we must do is import the intertools module, because this module has the cycle() function, which is needed to loop infinitely through a value.

We then create the variable, string1, which will contain the string you want to repeat infinitely. In this case, it is 'Game over'.

We then have our for loop which loops infinitely through the value we created in string1.

We then print out the value. This repeats 'Game over' infinitely until the user ends the loop such as by typing in 'Ctrl + C'.

Realize that you have to create a list and put the string in a list for it to infinitely loop the value.

If you put a standalone string for the cycle() function to loop through, it will not print out the string on its own line, as you may think. It will instead print out each character on its own line. The cycle() function will separate each character of the string and have each character on its own line.

This is shown in the code below.



Again, this is probably not what you want.

So cycle() wouldn't work with a standalone string to repeat the string infinitely but must the string must be placed in a list to achieve the right intended effect.

And this is how you can repeat a string infinitely in Python using the cycle() function of the intertools module.


Related Resources

How to Extract All Files and Folders from a Zip File in Python

How to Read the Contents of a Zip File in Python



HTML Comment Box is loading comments...