【发布时间】:2019-04-06 06:41:30
【问题描述】:
我只是想知道在打印行中包含变量的最佳方式是什么。
例如,这样做会更好:
print("The cost will be $" + str(cost) + ".")
或
print("The cost will be ${}.".format(cost))
谢谢, 大卫
附:在解释时,请注意我一般是编程新手,谢谢:D
【问题讨论】:
标签: python python-3.x
我只是想知道在打印行中包含变量的最佳方式是什么。
例如,这样做会更好:
print("The cost will be $" + str(cost) + ".")
或
print("The cost will be ${}.".format(cost))
谢谢, 大卫
附:在解释时,请注意我一般是编程新手,谢谢:D
【问题讨论】:
标签: python python-3.x
我会说目前,这更好:
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='')
【讨论】:
print(f'The cost will be ${cost}')