1.格式化

a = 3.1415926
print("圆周率是"+"%.2f"%a)
​​​​​​​

 

2.字符串的内建方法

我们可以使用 format() 方法组合字符串和数字!

示例一:

format() 方法接受传递的参数,格式化它们,并将它们放在占位符 {} 所在的字符串中:

age = 63 
txt = "My name is Bill, and I am {}"
print(txt.format(age))

示例二:

format() 方法接受不限数量的参数,并放在各自的占位符中:

quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

示例三:

可以使用索引号 {0} 来确保参数被放在正确的占位符中:

quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

示例四:

在占位符内,可以添加格式化类型以格式化结果:

txt = "For only {price:.2f} dollars!"
print(txt.format(price = 49))

可以使用命名索引 {price}、编号索引{0}、甚至空的占位符 {} 来标识占位符。

txt1 = "My name is {fname}, I'am {age}".format(fname = "Bill", age = 64)
txt2 = "My name is {0}, I'am {1}".format("Bill",64)
txt3 = "My name is {}, I'am {}".format("Bill",64)
print(txt1)
print(txt2)
print(txt3)

3.python内置的round()函数

round()如果只有一个数作为参数,不指定位数的时候,返回的是一个整数,而且是最靠近的整数。 一般情况是使用四舍五入的规则,但是碰到舍入的后一位为5的情况,如果要取舍的位数前的数是偶数,则直接舍弃,如果奇数则向上取舍。

 

4.利用 math 模块里 ceil 和 floor 方法

math模块的ceil(x):取大于或者等于x的最小整数 math模块的floor(x):取小于或者等于x的最大整数

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐