且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

多行返回语句

更新时间:2023-12-04 13:10:28

在 Python 中,打开括号会导致后续行被视为同一行的一部分,直到关闭括号.

In python, an open paren causes subsequent lines to be considered a part of the same line until a close paren.

所以你可以这样做:

def game(word, con):
    return (word + str('!') +
            word + str(',') +
            word + str(phrase1))

但在这种特殊情况下,我不建议这样做.我提到它是因为它在语法上是有效的,你可以在其他地方使用它.

But I wouldn't recommend that in this particular case. I mention it since it's syntactically valid and you might use it elsewhere.

您可以做的另一件事是使用反斜杠:

Another thing you can do is use the backslash:

def game(word, con):
    return word + '!' + \
           word + ',' + \
           word + str(phrase)
    # Removed the redundant str('!'), since '!' is a string literal we don't need to convert it

或者,在这种特殊情况下,我的建议是使用格式化的字符串.

Or, in this particular case, my advice would be to use a formatted string.

def game(word, con):
    return "{word}!{word},{word}{phrase1}".format(
        word=word, phrase1=phrase1")

这看起来在功能上等同于你在你身上做的事情,但我真的不知道.不过,在这种情况下,我会选择后者.

That looks like it's functionally equivalent to what you're doing in yours but I can't really know. The latter is what I'd do in this case though.

如果您想在 STRING 中换行,那么您可以在任何需要的地方使用\n"作为字符串文字.

If you want a line break in the STRING, then you can use "\n" as a string literal wherever you need it.

def break_line():
    return "line\nbreak"