[英]how to print a string a certain number of times on a line then move to a new line
I have the list ['a','b','c','d','e','f','g']
.我有列表['a','b','c','d','e','f','g']
。 I want to print it a certain way like this:我想像这样以某种方式打印它:
a b c
d e f
g
this is what I've tried:这是我试过的:
result = ''
for i in range(len(example)):
result += example[i] + ' '
if len(result) == 3:
print('\n')
print(result)
but with this I continue to get one single line但是有了这个我继续得到一条线
Iterate over a range of indices and step by 3
, creating slices of three elements at a time.遍历一系列索引并逐步执行3
,一次创建三个元素的切片。
>>> a = ['a','b','c','d','e','f','g']
>>> for i in range(0, len(a), 3):
... print(a[i:i+3])
...
['a', 'b', 'c']
['d', 'e', 'f']
['g']
>>>
To format the data, you could either join the slice with ' '
or expand it out and use the sep
argument to print
.要格式化数据,您可以将切片与' '
连接起来,或者将其展开并使用sep
参数进行print
。
>>> for i in range(0, len(a), 3):
... print(' '.join(a[i:i+3]))
...
a b c
d e f
g
>>> for i in range(0, len(a), 3):
... print(*a[i:i+3], sep=' ', end='\n')
...
a b c
d e f
g
>>>
The problem with the example code above is that len(result) will never be 3. result is always increased by a character plus a space, so its length will always be a multiple of 2. While you could adjust the check value to compensate, it will break if the list elements are ever more than 1 character.上面示例代码的问题是 len(result) 永远不会是 3。result 总是增加一个字符加上一个空格,所以它的长度总是 2 的倍数。虽然你可以调整检查值来补偿,如果列表元素超过 1 个字符,它将中断。 Additionally, you don't need to explicitly print a "\n"
in Python, as any print statement will automatically end with a new line character unless you pass a parameter to not do that.此外,您不需要在 Python 中显式打印"\n"
,因为任何打印语句都会自动以换行符结束,除非您传递一个参数来不这样做。
The following takes a different approach and will work for any list, printing 3 elements, separated by spaces, and then printing a new line after every third element.以下采用不同的方法,适用于任何列表,打印 3 个元素,以空格分隔,然后在每三个元素之后打印一个新行。 The end
parameter of print is what should be added after the other arguments are printed. print的end
参数是在其他arguments打印完之后应该加上的。 By default it is "\n", so here I use a space instead.默认情况下它是“\n”,所以这里我用一个空格代替。 Once the index counter exceeds the list size, we break out of the loop.一旦索引计数器超过列表大小,我们就跳出循环。
i = 0
while True:
print(example[i], end=' ')
i += 1
if i >= len(example):
break
if i % 3 == 0:
print() # new line
Using enumerate
使用enumerate
example = ['a','b','c','d','e','f','g']
max_rows = 3
result = ""
for index, element in enumerate(example):
if (index % max_rows) == 0:
result += "\n"
result += element
print(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.