如何打印“漂亮"Python 中的字符串输出 [英] How to Print "Pretty" String Output in Python

查看:30
本文介绍了如何打印“漂亮"Python 中的字符串输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含字段 classid、dept、coursenum、area 和来自 sql 查询的标题的字典列表.我想以人类可读的格式输出值.我在想每个顶部的列标题,然后在每一列中都有适当的输出,即:

I have a list of dicts with the fields classid, dept, coursenum, area, and title from a sql query. I would like to output the values in a human readable format. I was thinking a Column header at the top of each and then in each column the approrpiate output ie:

CLASSID     DEPT     COURSE NUMBER        AREA     TITLE
foo         bar      foo                  bar      foo
yoo         hat      yoo                  bar      hat

(显然是标准对齐/间距)

(obviously with standard alignment/spacing)

我将如何在 python 中完成此操作?

How would I accomplish this in python?

推荐答案

标准 Python 字符串格式可能够了.

# assume that your data rows are tuples
template = "{0:8}|{1:10}|{2:15}|{3:7}|{4:10}" # column widths: 8, 10, 15, 7, 10
print template.format("CLASSID", "DEPT", "COURSE NUMBER", "AREA", "TITLE") # header
for rec in your_data_source: 
  print template.format(*rec)

# assume that your data rows are dicts
template = "{CLASSID:8}|{DEPT:10}|{C_NUM:15}|{AREA:7}|{TITLE:10}" # same, but named
print template.format( # header
  CLASSID="CLASSID", DEPT="DEPT", C_NUM="COURSE NUMBER", 
  AREA="AREA", TITLE="TITLE"
) 
for rec in your_data_source: 
  print template.format(**rec)

使用对齐、填充和精确格式说明符以获得最佳结果.

Play with alignment, padding, and exact format specifiers to get best results.

这篇关于如何打印“漂亮"Python 中的字符串输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆