从for循环python中删除空行

时间:2013-06-28 10:59:46

标签: python for-loop

我有很多行在python中从for循环中打印出来,如下所示:

class Wordnet():

    def compose_line6(self, pointers, pointers_synset_type):    
        for A, B in zip(pointers, pointers_synset_type):
            self.line6 += 'http://www.example.org/lexicon#'+A+' http://www.monnetproject.eu/lemon#pos '+B+'\n'
        return self.line6

    def compose_line7(self, pointers, pointer_source_target):
        for A, B in zip(pointers, pointer_source_target):
            self.line7 += 'http://www.example.org/lexicon#'+A+' http://www.monnetproject.eu/lemon#source_target '+B+'\n'
        return self.line7

'\ n'就是这样,for循环不会只是在一个大块中打印出来,但这也会在每个循环的末尾添加一个空行。使用这种方法打印这些:

def compose_contents(self, line1, line2, line3, line4, line5, line6, line7):
    self.contents = '\n'.join([line1, line2, line3, line4, line5, line6, line7])
    return self.contents

并打印self.contents给出了这个:

http://www.example.org/lexicon#13796604 http://www.monnetproject.eu/lemon#pos n
http://www.example.org/lexicon#00603894 http://www.monnetproject.eu/lemon#pos a
http://www.example.org/lexicon#00753137 http://www.monnetproject.eu/lemon#pos v
http://www.example.org/lexicon#01527311 http://www.monnetproject.eu/lemon#pos v
http://www.example.org/lexicon#02361703 http://www.monnetproject.eu/lemon#pos v

http://www.example.org/lexicon#13796604 http://www.monnetproject.eu/lemon#source_target 0000
http://www.example.org/lexicon#00603894 http://www.monnetproject.eu/lemon#source_target 0401
http://www.example.org/lexicon#00753137 http://www.monnetproject.eu/lemon#source_target 0302
http://www.example.org/lexicon#01527311 http://www.monnetproject.eu/lemon#source_target 0203
http://www.example.org/lexicon#02361703 http://www.monnetproject.eu/lemon#source_target 0101

如何避免打印()中间的空行?

编辑:所有这些方法都在for循环中调用     def line_for_loop(self,file):         对于文件中的行:             self.compose_line6(self.pointers,self.pointers_synset_type)             self.compose_line7(self.pointers,self.pointer_source_target)             self.compose_contents(self.line1,self.line2,self.line3,self.line4,self.line5,self.line6,self.line7)

,打印件为print wordnet.contents

1 个答案:

答案 0 :(得分:2)

过滤掉空行:

def compose_contents(self, *lines):
    self.contents = '\n'.join([line for line in lines if line.strip()])
    return self.contents

通过使用*args任意位置参数语法,它支持任意数量的输入行。