使用 python 的字符串格式

String Formatting using python

有什么方法可以使用 PYTHON3

进行这种字符串格式化
*************Food*************
initial deposit        1000.00
groceries               -10.15
restaurant and more foo -15.89
Transfer to Clothing    -50.00

其中数字右对齐,文本左对齐

ledger = [

    {'amount':10000,'description': 'initial deposit'},
    {'amount':-10.15,'description': 'groceries'},
    {'amount':-15.89,'description': 'restaurant and more food costings'},
    {'amount':-50,'description': 'Transfer to Clothing'}
    
]

请注意,描述键的值可能取决于用户... 所以它可能会更长或者也可能不是这些

如果我这样做

string = ''
for dic in ledger:
    string += '{description:<23}{amount:>7.2f}'.format(**dic)
    string += '\n'

print(string)

输出是这样的...

initial deposit        10000.00
groceries               -10.15
restaurant and more food costings -15.89
Transfer to Clothing    -50.00

但我希望描述部分在数字之前停止

小数点也没有对齐

所以我还缺少什么 谢谢!!!!

您可以通过首先计算列的 with 然后使用 f-strings 来做到这一点。另外对于头部的table,str.center()也是有用的。尝试:

ledger = [{'amount': 10000, 'description': 'initial deposit'},
          {'amount': -10.15, 'description': 'groceries'},
          {'amount': -15.89, 'description': 'restaurant and more food costings'},
          {'amount': -50, 'description': 'Transfer to Clothing'}]

width_desc = max(len(d['description']) for d in ledger)
width_amnt = max(len(f"{d['amount']:.2f}") for d in ledger)

print('Food'.center(width_desc + 1 + width_amnt, '*'))
for d in ledger:
    print(f"{d['description']:{width_desc}} {d['amount']:>{width_amnt}.2f}")

# *******************Food*******************
# initial deposit                   10000.00
# groceries                           -10.15
# restaurant and more food costings   -15.89
# Transfer to Clothing                -50.00

通过使用 f-strings,你可以在 python 3 中做很多很酷的格式化事情。这个 guide 非常适合学习你可以在 python.

要对齐 table,您可以使用如下字段:

ages = {"Mike":10, "Leonardo":32, "Donatello":144, "Raphael":5}

for k, v in ages.items():
    print(f"{k:10}\t{v:10}")

哪个会输出

Mike            10        
Leonardo        32        
Donatello       144
Raphael         5

字符串开头的 f 表示它是 f 字符串。变量后的 :10 表示它将在十个字符宽的字段中对齐。默认情况下,字符串和大多数对象左对齐,而数字右对齐。要更改对齐方式,您可以在数字前使用 <> 选项,例如:<10。您可以自动确定字段宽度或轻松截断太长的字符串。