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

房东的猫 提交于 2019-12-11 08:32:42

问题


I have a function trip_cost which calculates the total cost of a vacation. If I want to print the result of the function I can do so without problem like so:

print trip_cost(city, days, spending_money)

However if I try to code a more presentable, user-friendly version using a string I get a Syntax Error: Invalid Syntax

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

How can this problem be solved?


回答1:


Use the format() string method:

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

Update for Python 3.6+:

You can use formatted string literals in Python 3.6+

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



回答2:


Use str.format():

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

See 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().




回答3:


Use str

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



回答4:


You can Use format

Or %s specifier

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

OR

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


来源:https://stackoverflow.com/questions/30076273/how-to-print-a-string-followed-by-the-result-of-a-function-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!