repeat string n times in python

How to Repeat String N Times in Python

Sometimes you may need to repeat a string multiple times in Python. This is mostly required if you need to quickly populate a file or create mock data for testing purpose. But this can be a tedious process to do it manually. Luckily, python provides an amazing shortcut for this purpose. In this article, we will learn how to repeat a string N times in python and also create a function that you can use easily in your code.


How to Repeat String N Times in Python

Here are the steps to repeat string N times in python.


1. Repeat String N Times

The basic syntax to repeat a string N times is to add * immediately after it, followed by the number of times you want to repeat the string. It is just like multiplying a string N times. Here is an example to repeat a string ‘abc’ 3 times.

>>> 'abc'*3
'abcabcabc'
>>> r='abc'*3
>>> print(r)
'abcabcabc'
>>> s='abc'
>>> r=s*3
>>> print(r)
'abcabcabc'


2. Function to Repeat String N times

Here is an simple function to repeat a string N times and return the repeated string

def repeat_string(input, no_of_times):
    return input*no_of_times

You can call it as

>>> print(repeat_string('abc',3))
'abcabcabc'


3. Function to Repeat String to Given Length

Sometimes you want to repeat a string up to a given length. In such cases, you can use the following function.

def repeat_string(input, target_length):
    no_of_repeats = target_length // len(input) + 1
    input_repeated = input * no_of_repeats
    input_target = input_repeated[:target_length]
    return input_target

repeated_string = repeat_string("abc", 3)



print(repeated_string)
'abcabcabc

In the above function we use floor division operator // to determine the number of times the input string needs to be repeated. Then we use * operator to repeat it. Then we use slicing operator to truncate the repeated string to target length. Finally, we return the string.

In this article, we have learnt how to repeat a string in Python N times.

Also read:

How to Delete Last Field in Linux
How to Harden Apache Server in CentOS
How to Display Specific Columns in Linux
How to List Active Connections in PostgreSQL
How to Create Swap Space in Ubuntu/Debian

Leave a Reply

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