python 字符串format使用
python字符串的格式化輸出
?
格式化字符串是程序設(shè)計語言中用于指定輸出參數(shù)的格式化與相對位置的字符串參數(shù)。其中的轉(zhuǎn)換說明用于把隨后的對應(yīng)一個或多個函數(shù)參數(shù)轉(zhuǎn)換為相應(yīng)的格式輸出:格式化字符串中轉(zhuǎn)換說明以外的其他字符原樣輸出。
| 1 | >>>"I like %s" |
在這個字符串中,有一個字符 %s 就是一個占位符,這個占位符可以被其他字符串取代
| 1 2 | >>>"I like %s"?%?"girl" 'I like girl' |
自Python2.6以后提倡使用字符串的 format() 方法:string.format(*args,**kwargs)
| 1 2 | >>>"I like {1} and {0}".format('girl','dog') 'I like dog and girl' |
| 1 2 | >>>"I like {0} and {1}".format('girl','dog') 'I like girl and dog' |
{0}和{1}作為占位符占據(jù)兩個位置,然后調(diào)用str.format()方法分別把“girl”和“dog”兩個參數(shù)傳入對應(yīng)的占位符。str.format()方法返回的是一個字符串(“I like girl and dog”)
既然是格式化,那么就一定會有各種方便適應(yīng)的格式,讓輸出的結(jié)果符合指定格式
| 1 2 | >>>"I like {0:5} and {1:>5}".format('girl','dog') 'I like girl? and?? dog' |
{0:5}表示第一個位置占用五個字符默認(rèn)左對齊,{1:>5}表示第二個位置占用五個字符表示右對齊
| 1 2 | >>>"I like {0:^5} and {1:^5}".format('girl','dog') 'I like girl? and? dog ' |
兩個占位符都占用五個字符,并且參數(shù)在五個占位符中居中對其
| 1 2 | >>>"I like {0:^5.2} and {1:^5.2}".format('girl','dog') 'I like? gi?? and? do? ' |
兩個占位符都占用五個字符,并且參數(shù)在五個占位符中居中對其,傳入的字符串只截取兩個字符。girl->gi? dog->do
str.format() 中除了可以傳入字符串,還可以傳入數(shù)字
| 1 | "I like {0:10d} and {1:10.1f}".format(520,5.20)<br>'I like??????? 520 and??????? 5.2' |
傳入數(shù)字默認(rèn)右對齊,{1:10.1f}中? .1? 表示保留小數(shù)點后一位,d代表整數(shù),f代表浮點數(shù),如果不在傳入浮點數(shù)的時候不用 f 則會出現(xiàn)下面情況
| 1 2 | >>>"I like {0:10} and {1:10.1}".format(520,5.20) 'I like??????? 520 and????? 5e+00' |
| 1 2 | >>>"I like {sex} and {pet}".format(pet?=?'dog',sex?=?'girl') 'I like girl and dog' |
這是一種關(guān)于字典的格式化方法
| 1 2 3 | >>>data?=?{'name':'jiaxiangfei','sex':'boy'} >>>'{name} is a {sex}'.format(**data) 'jiaxiangfei is a boy' |
str.format(*args,**kwargs) 只是字符串的格式化方法
轉(zhuǎn)載于:https://www.cnblogs.com/hanzeng1993/p/11236003.html
總結(jié)
以上是生活随笔為你收集整理的python 字符串format使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 敏感词检测算法
- 下一篇: python练习题-day25