问题描述
已经搜索了互联网试图解决这个问题,但没有运气.据我所知,您通常只有一个 return 语句,但是我的问题是我的 return 语句中需要换行,以便测试返回true".我试过的是抛出错误,可能只是一个新手错误.我当前没有尝试换行的功能如下.
Have scoured the interwebs trying to figure this out but with no luck. As far as I know you usually only have one return statement however my problem is that I need to have line breaks in my return statement in order for the testing to return 'true'. What I've tried is throwing up errors, probably just a rookie mistake. My current function with no attempts to make a line break is below.
def game(word, con):
return (word + str('!')
word + str(',') + word + str(phrase1)
换行符 (\n) 是否应该在 return 语句中起作用?这不在我的测试中.
Are new line breaks (\n) supposed to work in return statements? It's not in my testing.
推荐答案
在 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"
这篇关于多行返回语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!