【问题标题】:Align text when written list of tuples to txt file将元组列表写入 txt 文件时对齐文本
【发布时间】:2021-08-06 22:30:49
【问题描述】:

我正在尝试将元组列表写入 txt 文件并将其与左侧对齐。 (需要用制表符分隔) 这是元组列表:

list1 = [(1, "Banana", "Yellow"), (2 , "Apple", "Red"), (3, "Carrot", "Orange")]

这是我写的代码:

def write_fruit(list1,new_file):
if not isinstance(list1, list):
    raise ValueError("First input must be a list.")
header = "Num Fruit Color"
with open(new_file, "w") as output:
    output.write(header + "\n")
    for line in list1:
        if not isinstance(line[1], str):
            raise ValueError("Second input must be a str.")
        vals = " ".join(str(i) for i in line)
        output.write(vals + "\n")
print(write_fruit(fruit_list, "fruit_list.txt"))

我的 txt 文件如下所示:

Num  Fruit  Color
 1  Banana    Yellow
 2   Apple   Red
 3   Carrot    Orange

我需要它向左对齐,我看到了一些看起来像 {: >20} 的建议,但并没有真正理解其背后的逻辑,所以如果有不同的方法我会很高兴。

【问题讨论】:

  • 第一:我没有看到任何标签\t,你只使用空间
  • 使用格式化方法,可以在那里指定字段宽度。
  • 我不明白您是如何获得该文本文件的。您的代码在每个字段之间只放置一个空格,但每行的空格数不同。
  • 什么逻辑你不懂?格式化操作符{:>20} 的意思是将对应的值放在一个左对齐的 20 个字符的字段中。

标签: python list function tuples


【解决方案1】:

我建议basic python formatting"{:<5}{:10}{:10}\n"

  • {:<5} 表示最小长度为 5,带空格填充,左对齐,{:>5} 表示右对齐

  • {:10} 表示最小长度为 10,带有空格填充。

默认数字对齐是right,所以我们必须强制left,而字符串的默认值已经是left


def write_fruit(list1, new_file):
    if not isinstance(list1, list):
        raise ValueError("First input must be a list.")
    template = "{:<5}{:10}{:10}\n"
    header = "Num Fruit Color".split()
    with open(new_file, "w") as output:
        output.write(template.format(*header))
        for line in list1:
            if not isinstance(line[1], str):
                raise ValueError("Second input must be a str.")
            output.write(template.format(*line))

给予

Num  Fruit     Color     
1    Banana    Yellow    
2    Apple     Red       
3    Carrot    Orange    

【讨论】:

  • OP 说他不理解以前使用 {:&gt;20} 的答案。所以你需要解释这是在做什么。
  • @Barmar 刚刚编辑完毕
  • 太好了!我对它有点陌生,只是学习基础知识,这真的很有帮助!
【解决方案2】:

为了正确对齐,改变这个

header = "Num Fruit Color"

到这里

header = "Num\tFruit\tColor"

并改变它,

vals = " ".join(str(i) for i in line)

到这里

vals = "\t".join(str(i) for i in line)

所以你的代码变成了:

def write_fruit(list1,new_file):
    if not isinstance(list1, list):
        raise ValueError("First input must be a list.")
    header = "Num\tFruit\tColor"
    with open(new_file, "w") as output:
        output.write(header + "\n")
        for line in list1:
            if not isinstance(line[1], str):
                    raise ValueError("Second input must be a str.")
            vals = "\t".join(str(i) for i in line)
            output.write(vals + "\n")

fruit_list = [(1, "Banana", "Yellow"), (2 , "Apple", "Red"), (3, "Carrot", "Orange")]
print(write_fruit(fruit_list, "fruit_list.txt"))

在输出文件中给出输出为:

Num Fruit   Color
1   Banana  Yellow
2   Apple   Red
3   Carrot  Orange

     

【讨论】:

  • 谢谢,我想对于对齐我应该使用“\t”而不是“\n|
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-07
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 2017-11-06
  • 2015-01-21
  • 1970-01-01
相关资源
最近更新 更多