如何在 Python 中打印后跟函数结果的字符串

How to print a string followed by the result of a function in Python

我有一个函数 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)}")

使用字符串

print "Your total trip cost is: " + str(trip_cost(city, days, spending_money))

使用str.format():

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

String Formatting

format(format_string, *args, **kwargs) format() is the primary API method. It takes a format string and an arbitrary set of positional and keyword arguments. format() is just a wrapper that calls vformat().

您可以使用格式

或 %s 说明符

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

print "Your total trip cost is: %s"%(trip_cost(city, days, spending_money))