在Python中引用没有换行的长字符串
我正在尝试在Python中写一个很长的字符串,这个字符串会作为OptParser选项的帮助项显示。在我的源代码.py文件中,我想插入换行符,这样我的代码就不会占用太多行。但是,我不希望这些换行符影响到代码运行时这个字符串的显示效果。例如,我想这样写:
parser.add_option("--my-option", dest="my_option", nargs=2, default=None,
help='''Here is a long description of my option. It does many things
but I want the shell to decide how to display this explanation. However,
I want newlines in this string.''')
这样做的话,当我用--help调用我的程序时,我的选项解释会出现很多空白行。
我该怎么解决这个问题呢?
谢谢。
4 个回答
4
默认的帮助格式器会重新格式化字符串,这样你就可以在帮助信息中随意使用换行符:
>>> from optparse import OptionParser
>>> parser = OptionParser()
>>> parser.add_option('--my-option', help='''aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaa
... b
... c d
... e
... f''')
>>> parser.print_help()
Usage: bpython [options]
Options:
-h, --help show this help message and exit
--my-option=MY_OPTION
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaa b c d e f
如果你想去掉一些常见的前导空格,可以使用textwrap.dedent
:
>>> from optparse import OptionParser
>>> from textwrap import dedent
>>> parser = OptionParser()
>>> parser.add_option('--my-option', help=dedent('''\
... Here is a long description of my option. It does many things
... but I want the shell to decide how to display this
... explanation. However, I want newlines in this string.'''))
>>> parser.print_help()
Usage: [options]
Options:
-h, --help show this help message and exit
--my-option=MY_OPTION
Here is a long description of my option. It does many
things but I want the shell to decide how to display
this explanation. However, I want newlines in this
string.
10
你可以利用字符串字面量的并排放置来实现这个功能。在Python中,就像在C语言里一样,如果两个字符串字面量之间只有空格(包括换行符),编译器会把它们合并成一个完整的字符串,忽略空格。也就是说:
parser.add_option("--my-option", dest="my_option", nargs=2, default=None,
help='Here is a long description of my option. It does '
'many things but I want the shell to decide how to '
'display this explanation. However, I do NOT want '
'newlines in this string.')
我假设你说的“我想要”其实是指“我不想要”;-)。
注意你传给help
的每个字符串末尾的空格:你必须明确地加上这些空格,否则并排放置会把“words”合并成像doesmany
这样的词;-)。
需要注意的是,和一些回答和评论所说的完全不同,你绝对不需要那些丑陋且多余的加号或反斜杠——不需要加号,因为编译器会为你处理并排放置,也不需要反斜杠,因为这一组物理行实际上是一条逻辑行(因为开括号在这一组物理行结束之前是没有关闭的!)。
23
你可以像在C语言中那样把字符串连接在一起,所以 "foo" "bar"
和 "foobar"
是一样的,这意味着这样写应该能达到你想要的效果:
parser.add_option("--my-option", dest="my_option", nargs=2, default=None,
help="Here is a long description of my option. It does many things "
"but I want the shell to decide how to display this explanation. However, "
"I want newlines in this string.")
注意,因为整个内容都在括号里面,所以你不需要用反斜杠来换行。