字串格式化( 方式 與 format方式)

2022-06-16 23:21:12 字數 3122 閱讀 7293

1、百分號方式

%[(name)][flags][width].[precision]typecode

.precision   可選,小數點後保留的位數

typecode    必選

注:python中百分號格式化是不存在自動將整數轉換成二進位制表示的方式

#

%s可以接收字串,或任何型別

msg='

i am %s. my hobby is ball.

'%'manuel

'print

(msg)

m1='

you are so %s, %s is my lucky number.

'%('

cute

',2)

print

(m1)

#%d只能接收數字

m2='

age: %d

'%18

print

(m2)

#%f列印浮點數,.4代表保留小數點後4位

f='percent: %.4f

'%99.12345678

print

(f)#

列印百分號,用兩個百分號

p='percent: %.2f%%

'%54.157894

print

(p)#

用鍵的方式拼接字串

t3="

i am %(name)s ,age: %(age)d

"%print(t3)

執行結果:

2、format方式

[[fill]align][sign][#][0][width][,][.precision][type]

sign         【可選】有無符號數字#            【可選】對於二進位制、八進位制、十六進製制,如果加上#,會顯示 0b/0o/0x,否則不顯示

,            【可選】為數字新增分隔符,如:1,000,000

width       【可選】格式化位所佔寬度

.precision 【可選】小數字保留精度

type         【可選】格式化型別

傳入「 整數型別 」的引數

傳入「 浮點型或小數型別 」的引數

常用格式化:

tpl = "

i am {}, age {}, {}

".format("

seven

", 18, '

alex')

>>> i am seven, age 18, alex

tpl = "

i am {}, age {}, {}

".format(*["

seven

", 18, '

alex'])

>>> i am seven, age 18, alex

tpl = "

i am , age , really

".format("

seven

", 18)

>>> i am seven, age 18, really seven

tpl = "

i am , age , really

".format(*["

seven

", 18])

>>> i am seven, age 18, really seven

tpl = "

i am , age , really

".format(name="

seven

", age=18)

>>> i am seven, age 18, really seven

tpl = "

i am , age , really

".format(**)

>>> i am seven, age 18, really seven

tpl = "

i am , age , really

".format([1, 2, 3], [11, 22, 33])

>>> i am 1, age 2, really 3tpl = "

i am , age , money

".format("

seven

", 18, 88888.1)

>>> i am seven, age 18, money 88888.100000tpl = "

i am , age

".format(*["

seven

", 18])

>>> i am seven, age 18tpl = "

i am , age

".format(name="

seven

", age=18)

>>> i am seven, age 18tpl = "

i am , age

".format(**)

>>> i am seven, age 18tpl = "

numbers: ,,,,,

".format(15, 15, 15, 15, 15, 15.87623, 2)

>>> numbers: 1111,17,15,f,f, 1587.623000%tpl = "

numbers: ,,,,,

".format(15, 15, 15, 15, 15, 15.87623, 2)

>>> numbers: 1111,17,15,f,f, 1587.623000%tpl = "

numbers: ,,,,,

".format(15)

>>> numbers: 1111,17,15,f,f, 1500.000000%tpl = "

numbers: ,,,,,

".format(num=15)

>>> numbers: 1111,17,15,f,f, 1500.000000%

字串格式化 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...