[英]Is there a function in Python that checks the number of printouts of the output?
[英]I cant get my code to draw a number pattern with nested loops in Python that will align all number printouts in a neat manner
使用嵌套的 for 循環創建以下打印輸出:
應該從用戶那里讀取行數。 使用格式化的打印輸出,以便即使是兩位數的數字也能對齊。 • 所有打印的數字對應於列號。 • 如果列號小於行號,則不打印數字。 • 打印適當數量的空格以填充空列。
# Program to print a pattern with numbers
print("Program to print a pattern with numbers ")
print("-" * 50)
n = int(input("Please enter the number of rows "))
print("-" * 50)
for i in range(n + 1):
# Increase triangle hidden
for j in range(i):
print(" ", end=' ')
# Decrease triangle to include numbers in pattern not in increment
for j in range(i, n):
print(j + 1, end=" ")
print()
上面的代碼生成所需的 output,但數字在 2 位輸入中未對齊。 我如何格式化 iterables 以制作完美對齊的 output 打印輸出。
Output:
您可以使用str.rjust
將字符串右對齊。 只要您知道每條線的總長度,就可以輕松對齊每條線,使它們都在右側對齊:
>>> n = 5
>>> for i in range(1, n+1):
... print(''.join(str(j).rjust(3) for j in range(i, n+1)).rjust(n*3))
...
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
這就是您可以修改代碼以使用str.rjust
的方式。 將rjust(2)
中的2
調整為您想要的任何數字。
print("Program to print a pattern with numbers ")
print("-" * 50)
n = int(input("Please enter the number of rows "))
print("-" * 50)
for i in range(n + 1):
# Increase triangle hidden
for j in range(i):
print(" ".rjust(2), end=" ")
# Decrease triangle to include numbers in pattern not in increment
for j in range(i, n):
print(str(j+1).rjust(2), end=" ")
print()
對於您的示例,這給出了:
Program to print a pattern with numbers
--------------------------------------------------
Please enter the number of rows 12
--------------------------------------------------
1 2 3 4 5 6 7 8 9 10 11 12
2 3 4 5 6 7 8 9 10 11 12
3 4 5 6 7 8 9 10 11 12
4 5 6 7 8 9 10 11 12
5 6 7 8 9 10 11 12
6 7 8 9 10 11 12
7 8 9 10 11 12
8 9 10 11 12
9 10 11 12
10 11 12
11 12
12
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.