为什么我的返回函数不能按我希望的方式工作?(Python3)

2024-04-19 11:12:15 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能给我一些提示或想法来解释为什么会这样:

def fishstore(fish, price):
  total = "Your", fish, "costs", price, "$"
  return total
print (fishstore("sardines", 5))

显示如下:

('Your', 'sardines', 'costs', 5, '$')

而不是这样:

Your sardines costs 5 $

Tags: yourreturndefpricetotalprintfishcosts
2条回答

您正在返回一个元组,这就是正在打印的内容。返回多个以逗号分隔的项并不意味着print()会将它们视为单独的参数。否则,如何将元组打印为元组?你知道吗

如果要将元组的内容打印为单独的参数,请使用*argument调用语法:

print(*fishstore("sardines", 5))

*argument语法使您可以显式地将所有值解压到单独的项中,以便print()进行处理。你知道吗

这个函数不是很有用,真的。使用string formatting将项目和价格放在一个字符串中打印可能更有用:

def fishstore(fish, price):
    total = "Your {} costs {}$".format(fish, price)
    return total

这时print(fishstore("sardines", 5))就可以正常工作了。你知道吗

如果您使用的是Python3.6(或更新版本),那么也可以使用^{} formated string literals语法:

def fishstore(fish, price):
    total = f"Your {fish} costs {price}$"
    return total

您可以通过编码total = "Your " + fish + "costs " + price +"$"来替换字符串。我不太清楚为什么它会输出这样的列表,但是其余的代码看起来是正确的。你也可以做print ("Your %s cost %d $", fish, price)。你知道吗

在Python中,逗号不是concat。如果希望将其存储在列表中,也可以像其他人所评论的那样使用.join()函数。你知道吗

相关问题 更多 >