【问题标题】:String Formatting using python使用 python 格式化字符串
【发布时间】:2021-12-06 17:07:21
【问题描述】:

有没有办法使用 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

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

小数点也不对齐

所以我在这里还缺少什么 谢谢!!!!

【问题讨论】:

  • 也许 f-string 有帮助。
  • 是的!可以添加你的数据的python代码吗?
  • 所有 Python 格式化方法都允许您指定字段是左对齐还是右对齐。阅读文档。

标签: python string format


【解决方案1】:

您可以通过首先计算列的 with 然后使用 f 字符串来做到这一点。对于表格的标题,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

【讨论】:

    【解决方案2】:

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

    要对齐表格,您可以使用以下字段:

    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 表示它将在十个字符宽的字段中对齐。默认情况下,字符串和大多数对象左对齐,而数字右对齐。要更改对齐方式,您可以在数字之前使用 &lt;&gt; 选项,例如:&lt;10。您可以自动确定字段宽度或截断过长的字符串。

    【讨论】:

    • 如果我这样做ages = {"Mike":10, "Leonardo":32, "Donatello the Donny":144, "Raphael":5} # in the place of Donatello using _DONATELLO THE DONNY_ for k, v in ages.items(): print(f"{k:10}\t{v:7.2f}") 对齐不再起作用。有没有办法剪断其余的弦
    • 例如,您可以对字符串进行切片。如果将打印语句更改为print(f"{k[:10]:10}\t{v:10}"),它将切断字符串。
    • 或者如果您希望它自动确定设置最大长度的长度:MAX_WIDTH = 20 width = max(a for a in ages.values()) if width &gt; MAX_WIDTH: width = MAX_WIDTH for k, v in ages.items(): print(f"{k[:width]:{width}}\t{v:10}")
    猜你喜欢
    • 2012-07-25
    • 1970-01-01
    • 2019-11-28
    • 2011-07-28
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 2015-03-09
    相关资源
    最近更新 更多