Python知識點:字串格式化

似火如心發表於2020-10-31

字串格式化

1. format 字串格式化

1.1 位置引數對應

​ 位置引數對應,位置引數不等時會報錯

v = 'My name is {},age {}'.format('alex',24)   # 位置引數對應
print(v)
# =>My name is alex,age 24
v = 'My name is {},age {}'.format('alex')   # 不對應
print(v)
# 報錯

1.2 數值對應

v = 'My name is {0},age {1}'.format('alex',24)  # 0,1對應元組內的第0個和第1個元素
print(v)
# =>My name is alex,age 24
v = 'My name is {1},age {0}'.format('alex',24)  # 1,0對應元組內的第1個和第0個元素
print(v)
# =>My name is 24,age alex

1.3 字典對應傳值

v = 'My name is {name},age {age}'.format(name='alex',age=24)
print(v)
# =>My name is alex,age 24

2. % 字串格式化

2.1 直接print中表示

print('I am %s my hobby is chess' %'alex')
# => I am alex my hobby is chess

2.2 變數儲存

name = 'I am %s my hobby is chess' %'alex'
print(name)
# => I am alex my hobby is alex

2.3 %f、%s、%d表示

符號功能
%s列印字串
%d列印整數
%f列印浮點數
# %s:列印字串
print('I am %s ,my hobby is %s'%('alex','chess'))
# =>I am alex ,my hobby is chess

# %d:列印整數
print('my num is %d , your num is %d'%(100,80))
# =>my num is 100 , your num is 80

# %f:列印浮點數
print('my num is %f'%9.999666)
# =>my num is 9.999666

2.4 列印百分數

​ 列印百分數需要加兩個“%%”

print('my num is %f%%'%9.999666)
# =>my num is 9.999666%

示例:計算數值佔比多少

total = int(input('輸入總值:'))
num = int(input('輸入佔比:'))
percent = (num/total)*100
print('概率為 %s%%' %percent)  # 兩個百分號
# =>輸入總值:100
# =>輸入佔比:25
# =>概率為 25.0%

2.5 列印指定位數小數

​ ‘%.Xf’ %f方法(X:要保留的小數位數),會自動進行四捨五入

num = 10.123456
print('%f'%num)
# =>10.123456
print('%.1f'%num)   
# =>10.1
print('%.2f'%num)
# =>10.12
print('%.3f'%num)
# =>10.123
print('%.4f'%num)
# =>10.1235
print('%.5f'%num)
# =>10.12346

相關文章