【问题标题】:Best Way to Include Variable in Python3 [duplicate]在 Python3 中包含变量的最佳方法 [重复]
【发布时间】: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


    【解决方案1】:

    我会说目前,这更好:

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

    【讨论】:

    • 从 3.6 开始,f 弦更好。 print(f'The cost will be ${cost}')
    • @GWW 我会编辑
    • @GWW 完成编辑!!!
    猜你喜欢
    • 2015-09-30
    • 1970-01-01
    • 2021-03-22
    • 2013-04-07
    • 2020-04-25
    • 2019-05-13
    • 2011-03-23
    • 2014-10-14
    • 2016-03-15
    相关资源
    最近更新 更多