2011-09-14 22 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()を使用することができます:ちょうど",".join"\t".joinを置き換え、コンマについては

one two three 

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

出力。 Joinは、サンプルコードで使用されているようなタプルでも動作します(どのiterableでも動作します)。

+1

他の方法で値を書式設定する場合は、Python Docsの[Format String Syntax](http://docs.python.org/library/string.html#formatstrings)も参照してください。 – agf

+1

ありがとう!それはうまくいった! –

関連する問題