簡體   English   中英

如何在一行上打印一定次數的字符串然后移動到新行

[英]how to print a string a certain number of times on a line then move to a new line

我有列表['a','b','c','d','e','f','g'] 我想像這樣以某種方式打印它:

a b c 
d e f
g

這是我試過的:

result = ''
for i in range(len(example)):
    result += example[i] + ' '
    if len(result) == 3:
        print('\n')
print(result)

但是有了這個我繼續得到一條線

遍歷一系列索引並逐步執行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']
>>> 

要格式化數據,您可以將切片與' '連接起來,或者將其展開並使用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
>>> 

上面示例代碼的問題是 len(result) 永遠不會是 3。result 總是增加一個字符加上一個空格,所以它的長度總是 2 的倍數。雖然你可以調整檢查值來補償,如果列表元素超過 1 個字符,它將中斷。 此外,您不需要在 Python 中顯式打印"\n" ,因為任何打印語句都會自動以換行符結束,除非您傳遞一個參數來不這樣做。

以下采用不同的方法,適用於任何列表,打印 3 個元素,以空格分隔,然后在每三個元素之后打印一個新行。 print的end參數是在其他arguments打印完之后應該加上的。 默認情況下它是“\n”,所以這里我用一個空格代替。 一旦索引計數器超過列表大小,我們就跳出循環。

i = 0
while True:
    print(example[i], end=' ')
    i += 1
    if i >= len(example):
        break
    if i % 3 == 0:
        print()  # new line

使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM