Python program to repeat M characters of a string N times

Here, we are going to learn how to repeat a given number of characters (M) of a string N (given number) times using python program? By Suryaveer Singh Last updated : February 25, 2024

Problem statement

Given a string and we have to repeat it's M characters N times using python program.


Here we are provided with a string and a non-negative integer N, here we would consider that the front of the string is first M characters, or whatever is there in the string if the string length is less than M. Now our task is to return N copies of the front. Also, consider these cases,


    mult_times('Chocolate', 3, 2) = 'ChoCho'
    mult_times('Chocolate', 4, 3) = 'ChocChocChoc'
    mult_times ('jio', 2, 3) = 'jijiji'


Here we would first simply write code for string value equal to M or less. As we are unknown for the value of N we would store our string value in a variable and run a for loop for N times and each time we would store our value in that variable.

Let's understand this by Code, which would be easier to understand,


def mult_times(str, m, n):
    front_len = m
    if front_len > len(str):
        front_len = len(str)
    front = str[:front_len]

    result = ''
    for i in range(n):
        result = result + front
    return result

print (mult_times('IncludeHelp', 7, 5))
print (mult_times('prem', 4, 3))
print (mult_times('Hello', 3, 7))



To understand the above program, you should have the basic knowledge of the following Python topics:

Python String Programs »

Related Programs

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.