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