正确分割在屏幕上打印的长行的 Python 方法

0 投票
2 回答
911 浏览
提问于 2025-04-18 12:03

这可能是个小问题,但我想知道其他人是怎么处理这个的,或者有没有什么标准或推荐的方法。

下面有两种在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似乎有点违背Python提倡的简单原则,因为它使用了第二个print调用。

2 个回答

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
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.'''

个人来说,我不太喜欢这种方法,因为它看起来像是打乱了缩进,不过这只是我个人的看法。

撰写回答