9 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.''')
Run Code Online (Sandbox Code Playgroud)
上面的做事方式会让我这样做 - 当我用--help调用我的程序时,my-option的解释会有很多空白.
我怎样才能解决这个问题?
谢谢.
Gab*_*abe 19
您可以像在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.")
Run Code Online (Sandbox Code Playgroud)
请注意,您不需要反斜杠行继续符,因为整个内容都在括号内.
只是利用字符串文字并置 - 在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.')
Run Code Online (Sandbox Code Playgroud)
我假设"我想要"你的意思是"我不想要"这里;-).
请注意您传递的每个文字末尾的尾随空格help:您必须明确地将它们放在那里,否则并置会产生"单词",例如doesmany等等;-).
需要注意的是,从什么一些答案和意见要求非常不同,你最肯定不会需要难看的,冗余的长处和-或反斜杠在这里-因为编译器对你适用并列没有需要加号,没有反斜杠需要或者是因为这组物理线是一条逻辑线(由于开放式线路尚未关闭,直到物理线组结束!).
| 归档时间: |
|
| 查看次数: |
7473 次 |
| 最近记录: |