【问题标题】:How to print a float variable along with a string in the same line [closed]如何在同一行中打印浮点变量和字符串[关闭]
【发布时间】:2014-10-13 17:10:32
【问题描述】:

好的,所以我想打印一个浮点变量和一个句子(不仅仅是变量)。变量的名称是discount。我之前已经声明了这个变量。我可以让它单独打印变量。我做了print(float(discount)) 并显示了浮动,但我想打印"The discount is" (discount)。我试过了:

print("The discount is" float(discount))

那没有用。

【问题讨论】:

  • Python 3.x:print('The discount is', discount),Python 2.x:print 'The discount is', discount
  • 不能在 Python 中声明变量。您只能通过分配给它来初始化它。另外,为什么你需要在discount 上打电话给float?即使类型不是float,它也应该打印得很好。
  • @jpmc26 我非常精通 C++ 并且对 Python 很陌生,所以搞乱像这样的小东西让我感到困惑,因为它是不同的。这就是我遇到这个问题的原因。并且类型永远不会是 int 因为从 99 美元有 4 个不同百分比的折扣。 10%、20%、30% 和 40%。对不起,我不是说声明我的意思是分配。变量应为 99*.1(折扣 = 99*.1)。
  • @Jesse 我很高兴听到您正在学习 Python。 =) 我想你会发现 Python 的不同之处会让你重新思考很多范式和想法。 (对于来自 Java/.NET 背景的我来说,这肯定是有帮助的。)让我换个说法。 float 函数接受输入并将其转换为浮点数。为什么需要转换为浮点数?如果discount 恰好是字符串或整数或任何其他类型,那真的会有所不同吗,或者无论如何您都可以打印出来吗?或者你能确定它已经是一个你不需要转换的浮点数了吗?

标签: python string output


【解决方案1】:

您可以使用format函数来打印它。

print('The discount is {}'.format(float(discount)))

例子

discount = 15
print('The discount is {}'.format(float(discount)))

The discount is 15.0

由于您的示例似乎是货币,您可以使用以下内容打印两位小数

print("${:.2f}".format(float(discount)))

The discount is $15.00

【讨论】:

  • +1 适用于 2.7 和 3.x。 =)
【解决方案2】:

你需要在字符串文字和float(discount)之间使用逗号:

>>> discount = 25
>>> print("The discount is", float(discount))
The discount is 25.0
>>>

如果您使用的是 Python 2.x,则需要这样编写:

>>> discount = 25
>>> print "The discount is", float(discount)
The discount is 25.0
>>>

【讨论】:

    猜你喜欢
    • 2016-12-10
    • 1970-01-01
    • 2015-12-30
    • 2013-06-13
    • 2013-03-13
    • 1970-01-01
    • 2018-08-07
    相关资源
    最近更新 更多