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
Related posts:
How to Print in Same Line in Python
How to Randomly Select Item from List in Python
How to Store JSON to File in Python
How to Start Background Process in Python
How to Terminate Python Subprocess
How to Iterate Through List of Dictionaries in Python
How to Drop One or More Columns in Python Pandas
How to Get File Size in Python
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.