Skip to main content
 首页 » 编程设计

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

2025年05月04日11jpfss

我有一个函数 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+ 更新:

您可以使用 formatted string literals在 Python 3.6+ 中

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