2011-09-14 35 views
2

我有類似下面的文本文件之間的選項卡:打印一個元組與所述值

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

謝謝!

回答

12

如果你想加入一個字符串列表,你可以使用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文檔中的[Format String Syntax](http://docs.python.org/library/string.html#formatstrings)。 – agf

+1

謝謝!這工作! –