Python 重复一个字符串 n 次并打印 n 行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40008279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Repeat a string n times and print n lines of it
提问by Andrew Louis
i've been stuck on a question for some time now:
我已经被一个问题困住了一段时间:
I'm looking to create a python function that consumes a string and a positive integer. The function will print the string n times, for n lines. I cannotuse loops, i must only use recursion
我正在寻找创建一个使用字符串和正整数的 python 函数。该函数将打印字符串 n 次,共 n 行。我不能使用循环,我只能使用递归
e.g.
例如
repeat("hello", 3)
hellohellohello
hellohellohello
hellohellohello
whenever i try to make a function that does this, the function decreases the length of the string, progressively:
每当我尝试创建一个执行此操作的函数时,该函数都会逐渐减少字符串的长度:
e.g.
例如
repeat("hello", 3)
hellohellohello
hellohello
hello
here's what my code looks like:
这是我的代码的样子:
def repeat(a, n):
if n == 0:
print(a*n)
else:
print(a*n)
repeat(a, n-1)
any help would be appreciated, thanks!
任何帮助将不胜感激,谢谢!
回答by gokul_uf
One liner
一个班轮
def repeat(a,n):
print((((a*n)+'\n')*n)[:-1])
Let's split this up
让我们把它分开
a*n
repeats stringn
times, which is what you want in one line+'\n'
adds a new line to the string so that you can go to the next line*n
because you need to repeat itn
times- the
[:-1]
is to remove the last\n
asprint
puts a new-line by default.
a*n
重复字符串n
时间,这是您在一行中想要的+'\n'
在字符串中添加一个新行,以便您可以转到下一行*n
因为你需要重复它n
几次- 的
[:-1]
是消除最后\n
的print
默认提出一个新的行。
回答by zyxue
Try this
尝试这个
def f(string, n, c=0):
if c < n:
print(string * n)
f(string, n, c=c + 1)
f('abc', 3)
回答by Nf4r
You were really close.
你真的很亲近。
def repeat(a, n):
def rep(a, c):
if c > 0:
print(a)
rep(a, c - 1)
return rep(a * n, n)
print(repeat('ala', 2))
alaala
alaala
A function with closure would do the job.
一个带闭包的函数就可以完成这项工作。
回答by vishes_shell
So you just need extra argument that will tell you how many times you already ran that function, and it should have default value, because in first place function must take two arguments(str
and positive number).
所以你只需要额外的参数来告诉你你已经运行了多少次该函数,它应该有默认值,因为首先函数必须接受两个参数(str
和正数)。
def repeat(a, n, already_ran=0):
if n == 0:
print(a*(n+already_ran))
else:
print(a*(n+already_ran))
repeat(a, n-1, already_ran+1)
repeat('help', 3)
Output
输出
helphelphelp
helphelphelp
helphelphelp
helphelphelp
回答by Sam
You should (optionally) pass a 3rd parameter that handles the decrementing of how many lines are left:
您应该(可选)传递第三个参数来处理剩余行数的递减:
def repeat(string, times, lines_left=None):
print(string * times)
if(lines_left is None):
lines_left = times
lines_left = lines_left - 1
if(lines_left > 0):
repeat(string, times, lines_left)