使用制表符在元组中的值之间打印。

3

我有一个类似下面的文本文件:

this000is00a00test001251!!
this000is00a00test001251!!
this000is00a00test001251!!
this000is00a00test001251!!

我有以下代码来解析它:
def file_open():
    my_file = open(r'C:\Users\test\Desktop\parse_me.txt','r', encoding='cp1252')
    return my_file

def parse(current_line):
    seq_1 = (current_line[0:4])
    seq_2 = (current_line[7:9])
    seq_3 = (current_line[11:12])
    seq_4 = (current_line[14:18])
    seq_5 = (current_line[20:24])
    return(seq_1, seq_2, seq_3, seq_4, seq_5)

def export_file(current_file):
    for line in current_file:
        x = parse(line)
        print (x)

export_file(file_open())

这是我在解释器中得到的输出:

('this', 'is', 'a', 'test', '1251')
('this', 'is', 'a', 'test', '1251')
('this', 'is', 'a', 'test', '1251')
('this', 'is', 'a', 'test', '1251')

我希望看到的是这样格式化的文本:

this    is    a    test    1251

或者

this,is,a,test,1251

有什么想法吗?或者你有哪些好的链接可以解释3.0中的文本格式吗?
谢谢!
1个回答

13
如果您想要将一组字符串连接在一起,可以使用join()方法,如下所示:
list_of_strings = ['one', 'two', 'three']
print "\t".join(list_of_strings) #\t is the tab character

输出:

one    two    three

对于逗号,只需使用",".join来替换"\t".join即可。Join也可以与元组一起使用,就像你的示例代码中使用的那样(它可以与任何可迭代对象一起使用)。


1
如果您想以其他方式格式化值,请参阅Python文档中的格式化字符串语法 - agf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接