问题
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