重复一次字符串n次并打印n行

And*_*uis 2 python recursion

我已经被问了一段时间了:

我正在寻找创建一个消耗字符串和正整数的python函数.对于n行,该函数将打印字符串n次.我不能使用循环,我只能使用递归

例如

repeat("hello", 3)

hellohellohello
hellohellohello
hellohellohello
Run Code Online (Sandbox Code Playgroud)

每当我尝试创建一个执行此操作的函数时,该函数会逐渐减少字符串的长度:

例如

repeat("hello", 3)

hellohellohello
hellohello
hello
Run Code Online (Sandbox Code Playgroud)

这是我的代码的样子:

def repeat(a, n):
if n == 0:
    print(a*n)
else:
    print(a*n)
    repeat(a, n-1)
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激,谢谢!

gok*_*_uf 6

一个班轮

def repeat(a,n):
    print((((a*n)+'\n')*n)[:-1])
Run Code Online (Sandbox Code Playgroud)

让我们分开吧

  1. a*n 重复字符串n时间,这是你想要的一行
  2. +'\n' 在字符串中添加一个新行,以便您可以转到下一行
  3. *n因为你需要重复n一次
  4. [:-1]是消除过去的\n作为print默认把一个新行.


zyx*_*xue 5

尝试这个

def f(string, n, c=0):
    if c < n:
        print(string * n)
        f(string, n, c=c + 1)

f('abc', 3)
Run Code Online (Sandbox Code Playgroud)