如何在 Python 中打印后跟函数结果的字符串 [英] How to print a string followed by the result of a function in Python

查看:37
本文介绍了如何在 Python 中打印后跟函数结果的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数 trip_cost 可以计算假期的总成本.如果我想打印函数的结果,我可以毫无问题地这样做:

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)

但是,如果我尝试使用字符串编写更易于展示、用户友好的版本,我会收到 Syntax Error: Invalid Syntax

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)

如何解决这个问题?

推荐答案

使用 format() 字符串方法:

Use the format() string method:

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

Python 3.6+ 更新:

Update for Python 3.6+:

您可以在 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)}")

这篇关于如何在 Python 中打印后跟函数结果的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆