Python:右侧的字符串格式

时间:2018-12-12 13:24:11

标签: python string formatting string-formatting

这是我的源代码:

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()

6 个答案:

答案 0 :(得分:1)

将打印声明更改为此

print("{}. {:10}".format(i + 1, res[i])) # for left justify
print("{}. {:>10}".format(i + 1, res[i])) # for right justify

如果您需要更多有关操作方法的信息,请参阅此link

答案 1 :(得分:1)

您可以使用格式字符串在右边进行对齐。尝试使用此打印:

print("{}. {:>20}".format(i + 1, res[i]))

答案 2 :(得分:0)

尝试:

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()

答案 3 :(得分:0)

由于您不知道最后一个数字的位数,因此必须将结果存储在列表中,然后在打印时添加空格。

例如,将最后一个数字的长度作为字符串获取

Imports System.Data.SqlClient

Public Class VBNET_SQL_Datagridview_Search
    Dim connection As New SqlConnection("Server= DBserver;Database=HiddenDB;Integrated Security=SSPI;")
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    FilterData("")
End Sub


Public Sub FilterData(valueToSearch As String)
valueToSearch & "'%"
    Dim searchQuery As String = "SELECT * From database WHERE CONCAT(Sender, Recipient, TimeData) like '%" & valueToSearch & "%'"
    Dim command As New SqlCommand(searchQuery, connection)
    Dim adapter As New SqlDataAdapter(command)
    Dim table As New DataTable()
    adapter.Fill(table)
    NewMethod()
    DataGridView1.DataSource = table




End Sub

End Class

,然后遍历数组,添加所需的空格:

size = len(str(numbers[-1])))
padding = ""
for i in range(size):
    padding += " " 

答案 4 :(得分:0)

您需要指定格式宽度以使其正确地向右对齐。

代码:

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)

答案 5 :(得分:0)

尝试设置两个值的格式:

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::支持添加可变长度。