欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python?format格式化和數(shù)字格式化

 更新時間:2022年02月28日 10:30:40   作者:U盤失蹤了  
這篇文章主要介紹了python?format格式化和數(shù)字格式化,格式化字符串的函數(shù)?str.format(),它增強了字符串格式化的功能,基本語法是通過{}?和?:?來代替以前的?%?,下面內容介紹,需要的朋友可以參考一下

1.format() 基本用法

  • python2.6 開始,新增了一種格式化字符串的函數(shù)str.format(),
  • 它增強了字符串格式化的功能
  • 基本語法是通過{} 和 : 來代替以前的 % .
  • format 函數(shù)可以接受不限個參數(shù),位置可以不按順序。
a = "姓名:{0},年齡:{1}"
print(a.format("小明",18))
?
b = "姓名:{0},年齡:{1},{0}是個學生"
print(b.format("小明",18))
?
c = "姓名:{name},年齡:{age}"
print(c.format(age=19,name="小明"))

可以通過{索引}/{參數(shù)名},直接映射參數(shù)值,實現(xiàn)對字符串的格式化;

2.填充與對齊

  • 填充跟對齊一起使用
  • ^,<,> 分別是居中,左對齊,右對齊,后面帶寬度
  • # :號后面帶填充的字符,只能是一個字符,不指定的話默認是用空格填充
print("{:*>8}".format("245"))
?
print("我是{0},我喜歡語文{1:*<8}".format("小明","666"))
?
print("我是{0},我喜歡語文{1:*>8}".format("小明","666"))

3.數(shù)字格式化

  • # 浮點數(shù)通過 f,整數(shù)通過 d 進行需要的格式化。
a = "{0},錢:{1:.2f}"
print(a.format("小明",3333.23456))
test_0="{0:.2f}"
print(test_0.format(3.1415926))
?
test_1="{0:+.2f}"
print(test_1.format(3.1415926))
?
test_2="{0:.0f}"
print(test_2.format(3.1415926))
?
test_3="{0:0>2d}"
print(test_3.format(5))
?
test_4="{0:x<4d}"
print(test_4.format(5))
?
test_5="{0:,}"
print(test_5.format(1000000))
?
test_6="{0:.2%}"
print(test_6.format(0.25))
?
test_7="{0:.2e}"
print(test_7.format(10000000000))
?
test_8="{0:10d}"
print(test_8.format(13))
?
test_9="{0:<10d}"
print(test_9.format(13))
?
test_10="{0:^10d}"
print(test_10.format(13))

到此這篇關于python format格式化和數(shù)字格式化的文章就介紹到這了,更多相關python format格式化和數(shù)字格式化內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論