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

时间:2022-09-12 01:43:37

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:

我有一个函数trip_cost,它计算一个假期的总成本。如果我想打印函数的结果我可以这样做而没有问题:

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?

怎样才能解决这个问题?

4 个解决方案

#1


Use the format() string method:

使用format()字符串方法:

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

Update for Python 3.6+:

Python 3.6+的更新:

You can use formatted string literals in Python 3.6+

您可以在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().

format(format_string,* args,** kwargs)format()是主要的API方法。它采用格式字符串和一组任意位置和关键字参数。 format()只是一个调用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

或%s说明符

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))

#1


Use the format() string method:

使用format()字符串方法:

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

Update for Python 3.6+:

Python 3.6+的更新:

You can use formatted string literals in Python 3.6+

您可以在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().

format(format_string,* args,** kwargs)format()是主要的API方法。它采用格式字符串和一组任意位置和关键字参数。 format()只是一个调用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

或%s说明符

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))