如何在多行中断字符串创建,但包括内联注释

时间:2017-04-28 18:44:02

标签: python string comments

我想创建一个字符串,但包含每个部分的注释。在Python中,我可以在函数print("Hello " + # WORKS "World!") greeting = "Hello " + # FAILS "World!" print(greeting) 中执行此操作,但如果我创建变量,则无法执行此操作。

  File "space.py", line 4
    greeting = "Hello " + # FAILS
                                ^
SyntaxError: invalid syntax

引发错误:

greeting = "Hello " + \# FAILS
           "World!"

print(greeting)

我尝试过续行:

  File "line_continuation.py", line 4
    greeting = "Hello " + \# FAILS
                                 ^
SyntaxError: unexpected character after line continuation character
print("Hello "  + # WORKS
       "World!")

greeting =("Hello " + # WORKS TOO
           "World!")

print(greeting)

3 个答案:

答案 0 :(得分:2)

如果您想控制空间,您可以这样做:

print("This "  # comment 1
      "is "  # comment 2
      "a "  # comment 3
      "test")  # comment 4

s = ("This "  # comment 1
     "is "  # comment 2
     "a "  # comment 3
     "test")  # comment 4
print(s)

输出:

This is a test
This is a test

使用逗号会在每个字符串之间添加一个空格,并且特定于print。上面显示的方法适用于任何地方的字符串。

请注意,这将代表一个字符串,因此如果您想要注入变量,则需要在最后一行.format

在字符串周围使用()的做法经常与制作tuple相混淆,但除非它包含逗号,否则它不是元组。

s = ("Hello")
print(type(s), s)
s = ("Hello",)
print(type(s), s)

输出:

<class 'str'> Hello
<class 'tuple'> ('Hello',)

答案 1 :(得分:2)

您可以将字符串分成多行,只需将它们一个接一个地放入:

a = ("hello " # can use comments
    "world")
print(a)

b = "hello " "world" # this also works
print(b)

c = a " again" # but this doesn't, SyntaxError
print(c)

答案 2 :(得分:0)

我只是想通了。在正在构造的字符串部分周围添加括号可以起作用:

unsigned int x = -3365; printf("%u", x);