我有一个函数trip_cost,它计算假期的总费用。如果我想打印函数的结果,我可以这样做,而不会出现以下问题:

print trip_cost(city, days, spending_money)

但是,如果我尝试使用字符串编码一个更美观,更人性化的版本,则会得到Syntax Error: Invalid Syntax
print "Your total trip cost is: " trip_cost(city, days, spending_money)

这个问题怎么解决?

最佳答案

使用 format() 字符串方法:

print "Your total trip cost is: {}".format(trip_cost(city, days, spending_money))

Python 3.6及更高版本的更新:

您可以在Python 3.6+中使用formatted string literals
print(f"Your total trip cost is: {trip_cost(city, days, spending_money)}")

关于python - 如何在Python中打印字符串以及函数结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30076273/

10-12 12:38