Python简单的字符串循环

时间:2014-10-03 20:26:02

标签: python string

应该是什么样的:

enter word: word
enter number: 5

word
word+word
word+word+word
word+word+word+word
word+word+word+word+word

我有什么:

for i in range(1,number+1):
    print(word*i)

我也试过这样的事情:

for row in range(1,number+1):
    for number in range(1,row+1):
        print(word, end='+')
    print()

他们都没有按照要求工作。

感谢Cyber​​提供的答案,解决方案很棒而且简短,但是我试图用for循环和"结束"和" sep" (也许即使是循环),有没有办法只与那些人一起做?

1 个答案:

答案 0 :(得分:2)

def repeat(word, num):
    for i in range(1,num+1):
        print('+'.join(word for _ in range(i)))

测试

>>> repeat('hello',4)
hello
hello+hello
hello+hello+hello
hello+hello+hello+hello