Given a string and we have to repeat it's M characters N times using python program.
给定一个字符串,我们必须使用python程序将其重复M个字符N次。
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,
在这里,我们提供了一个字符串和一个非负整数N ,在这里我们将认为字符串的开头是前M个字符,或者如果字符串的长度小于M ,则字符串中的任何字符。 现在我们的任务是返回N份正面的副本 。 另外,考虑这些情况,
Example:
例:
mult_times('Chocolate', 3, 2) = 'ChoCho'
mult_times('Chocolate', 4, 3) = 'ChocChocChoc'
mult_times ('jio', 2, 3) = 'jijiji'
Solution:
解:
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.
在这里,我们首先简单地编写等于或小于M的字符串值的代码。 因为我们不知道N的值,所以我们将字符串值存储在变量中,并运行一次for循环 N次,每次我们将值存储在该变量中。
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
翻译自: https://www.includehelp.com/python/program-to-repeat-m-characters-of-a-string-n-times.aspx