我不明白 format() 和 ... (python) 之间有什么区别

编程入门 行业动态 更新时间:2024-10-26 13:21:45
本文介绍了我不明白 format() 和 ... (python) 之间有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

这里的新手很困惑.使用有什么区别:

Confused newbie here. What's the difference between using:

print ("So you are {0} years old".format(age))

print ("So you are", age, "years old")

两者都有效.

推荐答案

实际上有很大的不同.前者使用字符串的format 方法来创建一个字符串.后者,将几个参数传递给 print 函数,它将把它们全部连接起来,在它们之间添加一个空格(默认).

Actually there's a huge difference. The former use string's format method to create a string. The latter, pass several arguments to print function, which will concatenate them all adding a whitespace (default) between them.

前者要强大得多,例如,您可以使用格式语法 完成以下操作:

The former is far more powerful, for instance, you can use the format syntax to accomplish things like:

# trunc a float to two decimal places
>>> '{:.2f}'.format(3.4567)
'3.46'

# access an objects method
>>> import math
>>> '{.pi}'.format(math)
'3.141592653589793'

它类似于早期版本的python中使用的printf样式格式,带有%操作符:(即:"%d"%3) 现在 str.format() 被推荐用于 % 运算符,并且是 Python 3 中的新标准.

It is similar to printf style formats used in earlier versions of python with the % operator: (ie: "%d" % 3) Now str.format() is recommended over the % operator and is the new standard in Python 3.

这篇关于我不明白 format() 和 ... (python) 之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-28 06:40:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1169728.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:我不   有什么区别   format   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!