Q:

Python program to repeat M characters of a string N times

belongs to collection: Python String Programs

0

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

Question:

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,

Example:

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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,

Code:

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))

Output

IncludeIncludeIncludeIncludeInclude
prempremprem
HelHelHelHelHelHelHel

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to swap characters of a given strin... >>
<< Python program for slicing a string...