Repeat string n times with separator in Python

In this tutorial, you will learn how to repeat string n times with separator in Python.

First, you will take any string, in this case, I will use a variable called “string” to store our desired string and then we will use separators on the string.

string = "Welcome to codespeedy"

In Python, you can use both double quotes and single quotes for the string and you can also use a single quote inside a double quote and vice-versa. Later on in our code, we will use the input() method and will store it in a variable say n.

n = int(input())

this will take an integer as input and it will represent the amount of time we want to repeat our string. Now we will use “*” and this operator can be used to repeat the string as many numbers of times as you want, in this case, we want to repeat the string n times and then I will store the result in a variable say “repeated_string” and code for the same is:

repeated_string = string*n

After this, you will use a method knows as split(), this method splits up the complete string and then returns it as a list. The default separator is whitespace although you can take any separator you want. I will store this in a variable say “splitted_string” and the code for the same is:

splitted_string = repeated_string.split()

although we don’t have to print this, if you print the code above then you will get the following output and this will help you understand how split() method works.

['Welcome', 'to', 'codespeedy', 'Welcome', 'to', 'codespeedy', 'Welcome', 'to', 'codespeedy']

We can now use join function on the list that we obtained after using the split method, i.e on splitted_string. It just joins the elements and then returns it as a string after the elements have been joined by a separator. In this case, we will use separator as ‘-‘ although you can use anything you want in its place.

separator = '-'
separator = separator.join(splitted_string)

the output for the above code will be:


Note:- I have assumed the value of n to be 3 in the above example although you can take any value you want for n. 

Also read:

Leave a Reply

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