编写一个将字符串重复 n 次并将每次重复与另一个字符串分开的函数

0 python string repeat python-3.x

我正在尝试编写一个需要 3 个输入的函数:一个字符串(已命名word)、一个整数(已命名n)、另一个字符串(已命名delim',然后该函数必须重复命名word n时间的字符串(这很容易),并且在每次重复之间它都有插入名为 的字符串delim

我知道这段代码有效:

print('me', 'cat', 'table', sep='&')
Run Code Online (Sandbox Code Playgroud)

但这段代码没有:

print(cat*3, sep='&')
Run Code Online (Sandbox Code Playgroud)

我写的代码几乎没用,但我还是会发布它——可能还有我不知道的其他错误或不准确之处。

def repeat(word, n, delim):
    print(word*n , sep=delim)

def main():
    string=input('insert a string:  ')
    n=int(input('insert number of repetition:  '))
    delim=input('insert the separator:  ')

    repeat(string, n, delim)

main()
Run Code Online (Sandbox Code Playgroud)

例如,给定以下输入:

word='cat', n=3, delim='petting'
Run Code Online (Sandbox Code Playgroud)

我希望该程序回馈:

catpettingcatpettingcat
Run Code Online (Sandbox Code Playgroud)

sch*_*ggl 5

您可以使用可迭代解包并仅使用以下print功能:

def repeat(word, n, delim):
    print(*n*[word], sep=delim)
Run Code Online (Sandbox Code Playgroud)

或者只是使用str.join

def repeat(word, n, delim):
    print(delim.join(word for _ in range(n)))
Run Code Online (Sandbox Code Playgroud)


rok*_*rok 5

你正在寻找 print('petting'.join(["cat"]*3))

$ python3
Python 3.6.9 (default, Jan 26 2021, 15:33:00) 
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print('petting'.join(["cat"]*3))
catpettingcatpettingcat
>>> 
Run Code Online (Sandbox Code Playgroud)