Noob问题,但是: 假设你有一个,等于90;和b,等于100;你想回来 “90小于100” 如何让它返回(不打印)“90小于100”而不是“a小于b”
我尝试使用逗号,但是没有正确执行,它返回“(90,”小于“,100)”我猜你必须将a和b转换为字符串?
答案 0 :(得分:4)
>>> a = 90
>>> b = 100
>>> '{0} is less than {1}'.format(*sorted([a, b]))
'90 is less than 100'
如果你已经知道一个比另一个更大
,那就更简单了'{0} is less than {1}'.format(a, b)
使用.format
时,您不需要将任何变量转换为字符串,这就是它的优点!
答案 1 :(得分:1)
def main():
a = 90
b = 100
msg = foo(a,b)
print msg
def foo(a,b):
if a < b:
msg = "a = %d is less than b = %d " % (a,b)
return (msg)
elif a> b:
msg = "b = %d is less than a = %d " % (b,a)
return (msg)
else:
msg = "a = %d is eual to a = %d " % (a,b)
return (msg)
if __name__=="__main__": main()
答案 2 :(得分:0)
你可以像这样返回一个元组:
def func():
# do stuff
return (90, 'is less than', 100)
然后您可以通过执行类似
的操作来获取这些内容value1, text, value2 = func()
value1将等于90,文本将等于'小于',最后,value2将等于100
这是一种做法。这是另一个返回词典的人。
def func():
# do stuff
return {'a': 90,
'text': 'is less than',
'b': 100}
然后您可以这样使用它:
ret = func()
print ret['a'] # prints 90
print ret['text'] # prints is less than
print ret['b'] # prints 100
有很多方法可以做这样的事情。您甚至可以为此创建特定对象。这取决于您希望如何使用数据