Python程序将字符串的M个字符重复N次

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值