python - 在 Python3 中包含变量的最佳方法

标签 python python-3.x

我只是想知道在打印行中包含变量的最佳方法是什么。

例如,这样做会更好吗:

print("The cost will be $" + str(cost) + ".")

print("The cost will be ${}.".format(cost))

谢谢, 大卫

附注在解释时,请注意,我一般来说是编程新手,谢谢:D

最佳答案

我想说,目前,这更好:

print("The cost will be ${}.".format(cost))

因为不需要转换为字符串。

注意:如果你的Python版本超过3.5,请执行print(f'The cost will be${cost}'),因为它是最好的。

请注意,还有其他几种同样好的方法(适用于所有版本):

print('The cost will be$%s'%cost)

或者(也许不太好..):

print("The cost will be $",cost,".",sep='')

关于python - 在 Python3 中包含变量的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53111467/

相关文章:

python - PyQt5 中的 QTableView clicked.connect() 键盘滚动等效

json - 如何从python3中的json文件中检索所有 "name"和 "id"

python - 使用 MySQLdb 对非 utf 符号进行 utf8 编码

python - 使用 Posix 1e 在 Python 中检索默认 ACL

python - 使用角坐标收缩多边形

Python:SWIG:包装对结构的访问

Python - 将两个列表合并为一个 json 对象

python - 将 'CategorizedPlaintextCorpusReader' 转换为数据帧

python - 为什么urlopen可以下载谷歌搜索页面,不能下载谷歌学术搜索页面?

python - 用Python重写的C CRC计算方法好像不对