[英]What is the best way to format a function's return value to include spaces between variables?
如果不讓我的 foo function 包含實際的打印語句,並且只讓 foo 返回一個值,格式化 function 的最佳方法是什么? 例如,示例中的代碼將使主 function 打印“11”,而不是“1 1”或“1 & 1”。
我真的很感激你們!
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()
即使您提供的代碼與您的實際問題(在標題中)不匹配,我也會嘗試回答我認為是您的問題。
您可以嘗試返回一個在元素之間帶有空格的字符串,如下所示:
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)`
另一種方法是:
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
字符串連接的優點是您可以將任何字符(或字符串!)連接到str(x)
。 例如,您可以返回str(x)+"&"+str(y)
,對於 x=1,您將得到1&1
1!
在下圖中,我定義了foo(x,y)
三次,然后打印了 function 返回的值。注意:這是在交互式 Python IDLE Shell 中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.