[英]What is the best way to format a function's return value to include spaces between variables?
Without making my foo function contain an actual print statement, and only have foo return a value, what is the best way to format a function?如果不让我的 foo function 包含实际的打印语句,并且只让 foo 返回一个值,格式化 function 的最佳方法是什么? The code in the example will make the main function print "11" for example, instead of "1 1" or "1 & 1".例如,示例中的代码将使主 function 打印“11”,而不是“1 1”或“1 & 1”。
I really appreciate ya'll!我真的很感激你们!
def foo(x,y):
if x == y:
return x*2
def main():
x=input("Enter value 1")
y=input("Enter value 2")
print(int(max(x,y)))
main()
Even though the code that you've provided isn't matching your actual question (in the title), I'll try to answer what I think is your question.即使您提供的代码与您的实际问题(在标题中)不匹配,我也会尝试回答我认为是您的问题。
You can try returning a string with a space in between the elements, like so:您可以尝试返回一个在元素之间带有空格的字符串,如下所示:
def foo(x,y):
if x == y:
string = str(x)+" "+str(y) #there's a space between the quotation marks
return string
#this works even if x and y are not integers due to `str(x)` & `str(y)`
Another approach is:另一种方法是:
def foo(x,y):
if x==y:
n = 2 #this is the number of times you want x to appear in the output
x_new = x+" " #x concatenated with a space
return (x_new*n).rstrip()
#here, rstrip() is a string method that removes\
#whitespaces from the *right* end of the string
The advantage of concatenation of strings is that you can concatenate any character (or string!) to str(x)
.字符串连接的优点是您可以将任何字符(或字符串!)连接到str(x)
。 For example, you can return str(x)+"&"+str(y)
and you'll get 1&1
for x=1!例如,您可以返回str(x)+"&"+str(y)
,对于 x=1,您将得到1&1
1!
In the image below, I have defined foo(x,y)
thrice and then printed the value returned by the function. NOTE: This is in the interactive Python IDLE Shell.在下图中,我定义了foo(x,y)
三次,然后打印了 function 返回的值。注意:这是在交互式 Python IDLE Shell 中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.