【问题标题】:Printing int and float in Python [closed]在 Python 中打印 int 和 float [关闭]
【发布时间】:2021-12-26 20:18:06
【问题描述】:

考虑到下面的例子,为什么有人会选择第一个打印而不是第二个?

def main():
    name = input("Input your name:")
    age = int(input("Input you age:"))

    print("Your name is " + name + " and you are " + str(age) + " years old.")
    print("Your name is", name, "and you are" , age, "years old.")

if __name__ == "__main__":
    main()

在我看来print("text", var, "text") 更直接,因为不需要将我们的int 显式转换为str

print("text"+str(var)+"text") 格式是否有任何相关用例?

【问题讨论】:

  • + 通常连接字符串。当然,您希望能够连接字符串。在字符串中输出数字有更好的选择,但是将数字转换为字符串并连接它是一个简单的选项,因为存在类型转换和连接。不,它再好不过了,可能永远不应该是你的首选,但它就是这样。
  • 我认为这两种方法之间没有优势,只是口味和您正在做的打印类型的问题。

标签: python printing conceptual


【解决方案1】:

通常的做法是formatting like:

print(f"Your name is {name} and you are {age} years old.")

考虑到下面的例子,为什么有人会选择第一个打印而不是第二个?

好吧,第一种方法(字符串和表达式的连接转换为字符串)对我来说已经过时且无法使用,因为我们有正确的格式(如我上面的示例)。我们可以简单明了地构造任何我们想要的字符串。

如果我们将相同的逻辑应用于*args 方法,那么对于我来说,结果是一样的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 1970-01-01
    • 2012-04-19
    • 2018-03-14
    • 1970-01-01
    • 2012-01-21
    相关资源
    最近更新 更多