Python的字符串格式化

1. '%'字符串格式化html

#方法一: '%'
num = 10
print('--the number is %d--'%num) #output: "--the number is 10--"

print('the float number is %f'%-3.14) #output: "the float number is -3.140000",自動格式

print('the float number is %6.3f'%-3.14) #output: "the float number is -3.140"
#此時6.3的6表示寬度(包括正負號和小數點),3表示精度(也就是小數點位數,浮點型時)

print('the float number is %-9.3d'%-3) #output: "the float number is -003     "
#此時-9.3d,d表示整型,此時3表示顯示的數字寬度,不足的補零,9表示整個字符寬度,不足的補空格

print('the float number is %09.3f'%-3.14) #output: "the float number is -0003.140"
#浮點型,此時09.3表示精度爲3位,寬度爲9,不足的在前面補零

print('the float number is %-9.3f'%-3.14) #output: "the float number is -3.140   "
#此時-9.3表示精度爲3位,寬度爲9,不足的在後面補空格(由於沒有指定補零),最前面的負號'-'表示左對齊

2. format字符串格式化python

#方法二: format
print("what is your {}: {}!".format('name','Jack')) # output: "what is your name: Jack!"
#依次對應前面的括號,當括號內沒有值時

print('what is your {flag}?--- {1},and {0}? ---{myname}'.format(flag='name','you','Bob',myname='Lily'))
# SyntaxError: positional argument follows keyword argument,遵照python的參數賦值順序,關鍵字參數應該在後面

print('what is your {flag}?--- {1},and {0}? ---{myname}'.format('you','Bob',flag='name',myname='Lily'))
#output: "what is your name?--- Bob,and you? ---Lily",遵照python賦值順序

print('what is your {flag}?--- {1},and {0}? ---{myname}'.format('you','Bob','name','Lily'))
# KeyError: 'flag',由於前面的格式寫了'flag',可是後面沒有找到

print('what is your {2}?--- {1},and {0}? ---{3}'.format('you','Bob','name','Lily'))
#output: "what is your name?--- Bob,and you? ---Lily",以format中元組的索引賦值

print('what is your {1[0]}--- {0[1]},and {0[0]} ---{1[1]}'.format(('you','Bob'),('name','Lily')))
#output: "what is your name--- Bob,and you ---Lily",元組嵌套元組的索引賦值

3. format帶精度,對齊,補足位spa

## ^、<、>分別是居中對齊、左對齊、右對齊

print('{0}+{1}={2:$>6}'.format(2.4,3.1,5.5)) 
#"2.4+3.1=$$$5.5",>表示右對齊,6位寬度,$用於補足空位

print('{0}+{1}={2:$^6}'.format(2.4,3.1,5.5))
#"2.4+3.1=$5.5$$",^表示居中對齊

print('{0}+{1}={2:$<6}'.format(2.4,3.1,5.5))
#"2.4+3.1=5.5$$$",<表示左對齊

print('{0}+{1}={2:$<6.2f}'.format(2.4,3.1,5.5))
#"2.4+3.1=5.50$$",6.2f表示寬6位,精度是2位,浮點型

print('{0:$<6.2f}'.format(5.5)) #或者
print('{:$<6.2f}'.format(5.5))
#"5.50$$",只有一個參數時

4. format的字典傳遞關鍵字參數格式化、列表傳遞位置參數格式化3d

dict_para = {'flag':'question','name':'Jack'}
print("what is your {flag}: {name}!".format(**dict_para))
#"what is your question: Jack!",用字典傳遞參數,'**'用於收集關鍵字參數

list_para = ['question','Jack']
print("what is your {}: {}!".format(*list_para))
# "what is your question: Jack!",用列表傳遞參數,'*'用於收集參數

參考:code

http://www.javashuo.com/article/p-pjazggyv-bm.htmlorm

http://www.javashuo.com/article/p-dnqegsqk-by.htmlhtm

相關文章
相關標籤/搜索