Python入门基础教程_Python保留小数及对齐

XAMPP案例 747浏览
Python的保留小数：

``````median = 12.3004886
``````print(round(median, 2))   # 保留两位小数
``````print(round(median, 3))   # 保留三位小数
``````print(round(median, 4))   # 保留四位小数
``````'''
``````运行结果：
``````12.3
``````12.3
``````12.3005
````'''````

``````median = 12.3004886
``````print("%0.2f" % median)  # 保留两位小数
``````print("%0.3f" % median)  # 保留三位小数
``````print("%0.4f" % median)  # 保留四位小数
``````'''
``````运行结果：
``````12.30
``````12.300
``````12.3005
````'''````

``````# 首先引入decima函数
``````from decimal import Decimal
``````a=134.5657768
``````t=Decimal(“134.5657768”).quantize(Decimal(“0.00”))
````print(t)````

Python 输出字符串左对齐、右对齐、居中对齐

1.1、使用函数默认不带参数，则默认以空格填充（文字与空格总字符数等于输入的数字）。

``````# 代码
``````print("|", "Ursula".ljust(20), "|")   # 左对齐
``````print("|", "Ursula".center(20), "|")  # 居中对齐
``````print("|", "Ursula".rjust(20), "|")   # 右对齐
``````'''
``````运行结果:
``````| Ursula               |
``````|        Ursula        |
``````|               Ursula |
````'''````

1.2、函数中带参数，则以参数作为填充字符。

``````# 代码
``````print("|", "Ursula".ljust(20, "*"), "|")    # 左对齐
``````print("|", "Ursula".center(20, "*"), "|")   # 居中对齐
``````print("|", "Ursula".rjust(20, "*"), "|")    # 右对齐
``````'''
``````运行结果：
``````| Ursula************** |
``````| *******Ursula******* |
``````| **************Ursula |
````'''````

``````# 代码
``````print("|", format("Ursula","*<20"), "|")  # 左对齐
``````print("|", format("Ursula","*^20"), "|")  # 居中对齐
``````print("|", format("Ursula","*>20"), "|")  # 右对齐
``````'''
``````运行结果：
``````| Ursula************** |
``````| *******Ursula******* |
``````| **************Ursula |
````'''````