[英]Print x characters of a string over x lines
How can I write a function that prints a word over and over again, in sections of x
letters, until x
lines are reached.我如何编写一个函数,以x
字母的部分一遍又一遍地打印一个单词,直到到达x
行。 For example, the following:例如,以下内容:
nelio("ab",3)
print()
nelio("aybabtu",5)
will print:将打印:
aba
bab
aba
aybab
tuayb
abtua
ybabt
uayba
I started by writing a program, below, that just prints the whole word x
times, but can't figure out how to move forward from here.我首先在下面编写了一个程序,该程序只打印整个单词x
次,但不知道如何从这里向前推进。
def nelio(word,size):
i = 0
while i < size:
print(word)
i+=1
if __name__ == "__main__":
nelio("auto",3)
A fun little way of doing this is using a generator.一个有趣的小方法是使用生成器。 Normally you would just use itertools.cycle
, but if you say you can't import, no problem:通常你只会使用itertools.cycle
,但如果你说你不能导入,没问题:
def cycle_word(word):
while True:
for letter in word:
yield letter
And now you can use that to always get the next letter:现在您可以使用它来始终获取下一个字母:
def nelio(word, count):
letters = cycle_word(word)
for _ in range(count):
new_word = ''.join(next(letters) for _ in range(count))
print(new_word)
def nelio(word,size):
i = 0
for line in range(size):
for char in range(size):
print(word[i % len(word)], end="")
i += 1
print()
if __name__ == "__main__":
nelio("auto",3)
print()
nelio("ab",3)
print()
nelio("aybabtu",5)
Output:输出:
aut
oau
toa
aba
bab
aba
aybab
tuayb
abtua
ybabt
uayba
and if you do not want to deal with modulus, just expand the word first and then just do some simple slicing如果你不想处理模数,只需先扩展单词,然后做一些简单的切片
def nelio(word, repeat):
expanded_word = word
while len(expanded_word) < repeat * repeat:
expanded_word += word
start = 0
for _ in range(repeat):
end = start + repeat
print(expanded_word[start:end])
start += repeat
if __name__ == '__main__':
while True:
answer = input('Give me a word, repeat [hello, 2]: ')
word, repeat = answer.split(',')
nelio(word, int(repeat))
result结果
Give me a word, repeat [hello, 2]: ab, 3
aba
bab
aba
Give me a word, repeat [hello, 2]: aybabtu, 5
aybab
tuayb
abtua
ybabt
uayba
Give me a word, repeat [hello, 2]:
def nelio(word,size):
c=0
i=0
while c<size:
str=""
line_lenght=0
while line_lenght<size:
str+=word[i]
i+=1
i%=len(word)
line_lenght+=1
print(str)
c+=1
if __name__=="__main__":
nelio("aybabtu",5)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.