[英]Python: String formatting to the right side
這是我的源代碼:
def fibonacci_numbers():
how_many_numbers = int(input("\nHow many Fibbonacci numbers you want print: "))
i = 0
res = [0, 1]
while i < how_many_numbers:
res.append(sum(res[-2:]))
print("{}. {}".format(i + 1, res[i]))
i += 1
fibonacci_numbers()
現在的輸出是:
How many Fibbonacci numbers you want print: 30
1. 0
2. 1
3. 1
4. 2
5. 3
6. 5
7. 8
8. 13
9. 21
10. 34
11. 55
12. 89
13. 144
...
30. 514229
但是我需要這樣的東西:
How many Fibbonacci numbers you want print: 30
1. 0
2. 1
3. 1
4. 2
5. 3
6. 5
7. 8
8. 13
9. 21
10. 34
11. 55
12. 89
13. 144
...
30. 514229
等等。 這取決於我選擇的數字。 如果我使用50個數字,那么我需要更多的空格,但是所有內容都必須放在右側。
我該如何實現?
我嘗試使用{:>width}
和.rjust
方法,但無法獲取。
有沒有簡單的解決方案?
或者,也許我需要再做一個循環並在那里打印?
最終解決方案:
感謝您的回答。 我拿起其中一些,我做到了:
def fibonacci_numbers():
how_many_numbers = int(input("\nHow many Fibbonacci numbers you want print: "))
i = 0
res = [0, 1]
while i < how_many_numbers:
res.append(sum(res[-2:]))
i += 1
size_of_i = len(str(i))
i = 0
for num in res[:-1]:
size = len(str(res[-2]))
print("{:<{width_of_i}} {:>{width}}".format(str(i)+":", num, width_of_i=size_of_i + 1, width=size))
i += 1
fibonacci_numbers()
將您的印刷聲明更改為此
print("{}. {:10}".format(i + 1, res[i])) # for left justify
print("{}. {:>10}".format(i + 1, res[i])) # for right justify
如果您需要更多有關操作方法的信息,請參考此鏈接
您可以使用格式字符串在右對齊。 嘗試以下方法進行打印:
print("{}. {:>20}".format(i + 1, res[i]))
嘗試:
def fibonacci_numbers():
how_many_numbers = int(input("\nHow many Fibbonacci numbers you want print: "))
i = 0
res = [0, 1]
while i < how_many_numbers:
res.append(sum(res[-2:]))
print("{}. \t\t{}".format(i + 1, res[i]))
i += 1
fibonacci_numbers()
由於您不知道最后一個數字的位數,因此必須將結果存儲在列表中,然后在打印時添加空格。
例如,獲取最后一個數字的長度作為字符串
size = len(str(numbers[-1])))
padding = ""
for i in range(size):
padding += " "
然后遍歷數組,添加所需的空格:
for num in numbers:
print(padding[len(str(num)):] + str(num))
您需要指定格式寬度以使其正確地向右對齊。
碼:
def fibonacci_numbers(format_width):
how_many_numbers = int(input("\nHow many Fibbonacci numbers you want print: "))
i = 0
res = [0, 1]
while i < how_many_numbers:
res.append(sum(res[-2:]))
# Here we specify alignment to right with certain width
# which is >= number of digits of the largest integer in your sequence.:
print("{}. {:>{width}}".format(i + 1, res[i], width=format_width))
i += 1
fibonacci_numbers(30)
嘗試格式化兩個值:
import math
def fibonacci_numbers():
how_many_numbers = int(input("\nHow many Fibbonacci numbers you want print: "))
i = 0
res = [0, 1]
for i in range(how_many_numbers):
res.append(sum(res[-2:]))
digits = int(math.log10(res[i]))+1
ind_digits = int(math.log10(how_many_numbers-1))+2
for i in range(how_many_numbers):
print("{:<{ind_digits}} {:>{digits}}".format("{}.".format(i + 1), res[i], ind_digits=ind_digits, digits=digits))
fibonacci_numbers()
UPD:支持添加可變長度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.