首页 > 解决方案 > Python CLI 字符串格式化成列

问题描述

我正在开发一个用于连接到 WPE 的 API 的 CLI 应用程序,同时自学一些 Python。我点击 API 并填充本地 sqlite 数据库,然后显示该数据库中的记录。

    # pull all our installs
    _ins = self._db.get_all_installs( )

    # fire up and index
    _idx = 1

    # fire up a dict object to hold the selectable item
    _selectable = []

    # loop over the results
    for _row in _ins:

        # gather up some info and through them into re-usable variables
        _wpe_id = _row[2]
        _name = _row[3]
        _environ = _row[4]

        # build a "menu" string
        _menu_str = "{}) {} - {}".format( _idx, _name, _environ )

        # add the items to a dict object
        _selectable.append( _wpe_id )

        # increment the index
        _idx += 1

        # display the item
        if _idx % 3 == 0:

            print("here, maybe??")

        # display the item
        print( _menu_str )

我正在努力弄清楚的是如何让它分解单行单行输出。本质上,我想做的是将其视为 3 列“菜单”。我怎样才能做到这一点?

现在,我有 300 多条记录,一次输出 1 行。喜欢:

1) Row 1
2) Row 2
3) Row 3

我想做的是:

1) Row 1       2) Row 2       3) Row 3

ETC...

我怎样才能做到这一点?

标签: pythonstring

解决方案


您可以使用函数end的可选参数print

print(_menu_str, end='')

删除不需要的\n.

在你的代码中,你会有这样的东西:

if _idx % 3 == 2:
    print(_menu_str, end='')
else:
    print(_menu_str)

推荐阅读