打印一个元组,其值之间有一个制表符

发布于 2024-12-05 04:49:23 字数 1072 浏览 2 评论 0原文

我有一个如下所示的文本文件:

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 中的文本格式吗?

谢谢!

I have a text file like the one below:

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

I have the following code to parse through it:

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())

Here is the output I get in the interpreter:

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

What I want to see is the text formatted like this:

this    is    a    test    1251

or

this,is,a,test,1251

Any ideas? Or do you have any good links that explain text formatting in 3.0?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

枉心 2024-12-12 04:49:23

如果要连接字符串列表,可以使用 join(),如下所示:

list_of_strings = ['one', 'two', 'three']
print "\t".join(list_of_strings) #\t is the tab character

输出:

one    two    three

对于逗号,只需将 "\t".join 替换为 “,”.join。 Join 还可以使用示例代码中使用的元组(它可以使用任何可迭代对象)。

If you want to join a list of strings, you can use join() like so:

list_of_strings = ['one', 'two', 'three']
print "\t".join(list_of_strings) #\t is the tab character

Output:

one    two    three

For commas, just replace "\t".join with ",".join. Join will also work with tuples as used in your example code (It works with any iterable).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文