Python PEP8打印不带索引的包装字符串

2024-10-04 09:29:25 发布

您现在位置:Python中文网/ 问答频道 /正文

可能有一个简单的答案,只是不知道如何从我的搜索中挑出它。在

我在python代码中坚持使用PEP8,目前正在为我正在编写的脚本使用OptionParser。为了防止行超出带80的值,我在需要的地方使用反斜杠。在

例如:

if __name__=='__main__':
    usage = '%prog [options]\nWithout any options, will display 10 random \
    users of each type.'
    parser = OptionParser(usage)

反斜杠后的缩进将导致:

^{pr2}$

“随机”之后的间隙让我很烦。我可以做:

 if __name__=='__main__':
    usage = '%prog [options]\nWithout any options, will display 10 random \
 users of each type.'
    parser = OptionParser(usage)

但这也让我很恼火。这看起来很傻:

 if __name__=='__main__':
    usage = ''.join(['%prog [options]\nWithout any options, will display',
                     ' 10 random users of each type.'])
    parser = OptionParser(usage)

一定有更好的办法吗?在


Tags: ofnameifmaindisplayusageanyrandom
3条回答

这是有效的:

if __name__=='__main__':
    usage = ('%prog [options]\nWithout any options, will display 10 random '
    'users of each type.')
    parser = OptionParser(usage)

尽管我会这样说:

^{pr2}$

(所以当字符串中有一个\n时,以及当我需要对源代码进行文字包装时,我会开始一个新行。)

使用automatic string concatenation+implicit line continuation

long_string = ("Line 1 "
               "Line 2 "
               "Line 3 ")


>>> long_string
'Line 1 Line 2 Line 3 '

试试这个:

if __name__=='__main__':
    usage = '%prog [options]\nWithout any options, will display 10 random ' \
    'users of each type.'
    parser = OptionParser(usage)

相关问题 更多 >