Print a string N number of times in Python

In this article, we will learn how to print a string N number of times using Python. So, here we have to declare first what is a string. Therefore, we can go through our topic and also try to capture some basic knowledge.

What is the String?

Each programming language contains a set of characters that is used to communicate with the computer. A finite sequence of characters or special characters is called a string.

Now, we have to print a string multiple times as given by the user. So, let’s do an example.

Suppose, we have a string called “Money Heist”. Then the user will give the input i.e. how many times it will be printed. Let’s give it 5. So, the output will become “Money Heist Money Heist Money Heist Money Heist Money Heist”.

Let’s do the coding portion.

Program Code

Below is the Python code to print a string N number of times:

#creating a function 
def string_print(n):
    print("THE STRING IS 'Money Heist'")
    print("The string will be printed", n ,"times")
    for i in range(n):
        print("Money Heist")

#input function
string_print(5)

OUTPUT:

THE STRING IS 'Money Heist'
The string will be printed 5 times
Money Heist
Money Heist
Money Heist
Money Heist
Money Heist

Explanation:

In this code, you can see that we have used “for loop” in our program. So, the complexity of the program O(n^n). So, this complexity is not good for this program. So, we have to reduce the time complexity and modify our program.

Program Code

#creating a function 
def print_string(n):
    print("THE STRING IS 'Money Heist'")
    print("The string will be printed", n ,"times")
    return (" Money Heist " * n)

#input function
print_string(5)

OUTPUT:

THE STRING IS 'Money Heist'
The string will be printed 5 times
' Money Heist  Money Heist  Money Heist  Money Heist  Money Heist '

Explanation:

Now, this program takes less time than the previous program. So, we can use this method to get our output.

You can also view other articles.

Leave a Reply

Your email address will not be published. Required fields are marked *