拆分长行打印到python正确的屏幕

时间:2014-07-03 20:05:05

标签: python pep8

这可能是一个愚蠢的问题,但我想知道其他人如何处理这个问题,或者是否有标准/推荐的解决方法。

以下是在python中将其打印到屏幕时拆分长文本行的两种方法。应该使用哪一个?

选项1

if some_condition: # Senseless indenting.
    if another condition: # Senseless indenting.
        print 'This is a very long line of text that goes beyond the 80\n\
character limit.'

选项2

if some_condition: # Senseless indenting.
    if another condition: # Senseless indenting.
        print 'This is a very long line of text that goes beyond the 80'
        print 'character limit.'

我个人觉得选项1 丑陋,但选项2 似乎会违反通过第二次print调用来保持简单的pythonic方式。

2 个答案:

答案 0 :(得分:2)

一种方法可以使用括号:

print ('This is a very long line of text that goes beyond the 80\n'
       'character limit.')

当然,有几种方法可以做到这一点。另一种方式(如评论中所示)是三重引用:

print '''This is a very long line of text that goes beyond the 80
character limit.'''

就个人而言,我不喜欢那个,因为它似乎打破了缩进,但那只是我。

答案 1 :(得分:1)

如果您有一个长字符串并且想要在适当的位置插入换行符,textwrap模块提供了执行此操作的功能。例如:

import textwrap

def format_long_string(long_string):
    wrapper = textwrap.TextWrapper()
    wrapper.width = 80
    return wrapper.fill(long_string)

long_string = ('This is a really long string that is raw and unformatted '
               'that may need to be broken up into little bits')

print format_long_string(long_string)

这导致打印以下内容:

This is a really long string that is raw and unformatted that may need to be
broken up into little bits