Python 2.7:我只是没有正确填充

Python 2.7: ljust not padding correctly

以下代码未正确填充字符串

    for pre, fill, node in anytree.RenderTree(tree):

        prefix = ("{pre_print}{node_print}".format(pre_print=pre.encode('utf-8'), node_print=node.name)).ljust(120, '-')
        f.write("{pref}> {status}".format(pref=prefix, status=node.status.message()))
        f.write("\n")

我得到的一些输出是(为了便于阅读,我缩短了行填充):

├── modelo_srtm_30_nuevo----------------------------------> No cumple regla
├── modelos_externos--------------------------------------> Ok
│   ├── .snapshot---------------------------------------> No cumple regla
│   ├── 2017 - Aguas Blancas----------------------------> No cumple regla

pre 改变时,该行不再是它应该的长度。

编辑:以下代码演示了问题,创建了一个示例树并将其打印出来:

import anytree


root = anytree.Node(name="root")
child_1 = anytree.Node(name="child_1", parent=root)
grandchild_11 = anytree.Node(name="grandchild_11", parent=child_1)
child_2 = anytree.Node(name="child_2", parent=root)
grandchild_21 = anytree.Node(name="grandchild_21", parent=child_2)
child_3 = anytree.Node(name="child_3", parent=root)
grandchild_31 = anytree.Node(name="grandchild_31", parent=child_3)

filename = "test_tree.txt"

with open(filename, "wt") as f:

    for pre, fill, node in anytree.RenderTree(root):

        prefix = ("{pre_print}{node_print}".format(pre_print=pre.encode('utf-8'), node_print=node.name)).ljust(40, '-')
        f.write("{pref}> {status}".format(pref=prefix, status="testing..."))
        f.write("\n")

正如 Antti 暗示的那样,在编码后进行对齐不会产生非常丰硕的结果。先尝试对齐,然后 然后 编码:

with open(filename, "wt") as f:
    for pre, fill, node in anytree.RenderTree(root):
        prefix = (u"{pre_print}{node_print}".format(pre_print=pre, node_print=node.name)).ljust(40, '-').encode("utf-8")
        f.write("{pref}> {status}".format(pref=prefix, status="testing..."))
        f.write("\n")

结果:

root------------------------------------> testing...
├── child_1-----------------------------> testing...
│   └── grandchild_11-------------------> testing...
├── child_2-----------------------------> testing...
│   └── grandchild_21-------------------> testing...
└── child_3-----------------------------> testing...
    └── grandchild_31-------------------> testing...