python的字串格式化有兩種方式: 百分號方式、format方式
1、百分號方式
%[(name)][flags][width].[precision]typecode
width 可選,占有寬度
.precision 可選,小數點後保留的位數
typecode 必選
常用格式
tpl = "i am %s
" % "
alex
"tpl = "
i am %s age %d
" % ("
alex
", 18)
tpl = "
i am %(name)s age %(age)d
" %
tpl = "
percent %.2f
" % 99.97623tpl = "
i am %(pp).2f
" %
tpl = "
i am %.2f %%
" %
2.format格式化
常用格式:
tpl = "i am {}, age {}, {}
".format("
seven
", 18, '
alex')
tpl = "
i am {}, age {}, {}
".format(*["
seven
", 18, '
alex'])
tpl = "
i am , age , really
".format("
seven
", 18)
tpl = "
i am , age , really
".format(*["
seven
", 18])
tpl = "
i am , age , really
".format(name="
seven
", age=18)
tpl = "
i am , age , really
".format(**)
tpl = "
i am , age , really
".format([1, 2, 3], [11, 22, 33])
tpl = "
i am , age , money
".format("
seven
", 18, 88888.1)
tpl = "
i am , age
".format(*["
seven
", 18])
tpl = "
i am , age
".format(name="
seven
", age=18)
tpl = "
i am , age
".format(**)
tpl = "
numbers: ,,,,,
".format(15, 15, 15, 15, 15, 15.87623, 2)
tpl = "
numbers: ,,,,,
".format(15, 15, 15, 15, 15, 15.87623, 2)
tpl = "
numbers: ,,,,,
".format(15)
tpl = "
numbers: ,,,,,
".format(num=15)
字串格式化 format
tp1 i am age format seven 18,alex print tp1 fill align sign0,type 空格 正號空格,負號加負 可選 為數字新增分隔符,如 1,000,000 width 可選 格式化位所佔寬度 precision 可選 小數字保留精度 type 可選 ...
format 格式化字串
1.format 格式化字串 1 順序傳參 2 索引傳參 3 關鍵字傳參 4 容器型別傳參 代表的是佔位符2.順序傳參 strvar 向 開了一槍 res strvar.format 光頭強 熊二 print res 3.索引傳參 strvar 給乙個平底鍋 res strvar.format 灰太...
format格式化字串
1 語法結構 字串型別格式化採用format 方法,基本使用語法結構是 模板字串 format 逗號分隔的引數 呼叫format 方法後會返回乙個新的字串,引數從索引0 開始。計算機 的cpu 佔用率為 format 2016 12 31 python 10 2016 12 31 計算機python...