python 格式化字符串_Python字符串三种格式化输出
生活随笔
收集整理的這篇文章主要介紹了
python 格式化字符串_Python字符串三种格式化输出
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
字符串格式化輸出是python非常重要的基礎語法,今天就把三種格式化輸出做一個簡單的總結,希望對大家有幫助。
格式化輸出:內容按照一定格式要求進行輸出。
1.使用占位符%輸出
python2.6版本之前,使用%格式化字符串沿用的是C語言的輸出格式。
使用說明:
print("格式化字符串" % 變量)#變量超過2個使用元組格式:
print("格式化字符串" % (變量1,變量2))
使用%占位符表示字符串中變量位置。
傳入的值要與%占位符的變量一一對應。
其中,%s表示字符串,%d表示整數,%f表示小數(默認保留小數點后6位,%.2f保留兩位小數),存在格式化標志時,需要用 %%表示一個百分號。name='xiaoming' age=12 print("My name is %s,My age is %d" %(name,age)) #輸出:My name is xiaoming,My age is 12
2.format格式化
format是python2.6新增的一個格式化字符串的方法,相比%格式化方法有如下優點:
- 單個參數可以多次輸出,參數順序可以不相同
- 填充方式十分靈活,對齊方式十分強大
- 官方推薦用的方式
使用說明:
print("...{索引}, ... , {索引}, ...".format(值1, 值2)) #索引{}為空,默認按照順序取值 print("...{key1}, ... , {key2}, ...".format(key1=value,key2=value)) name='xiaoming' age=12 print('My name is {}, My age is {}'.format(name,age)) print('My name is {0}, My age is {1}'.format(name,age)) print('My name is {name}, My age is {age}'.format(name='xiaoming',age=12)) #輸出:My name is xiaoming,My age is 12format進階
1.填充對齊
# 先取到值,然后在冒號后設定填充格式:{索引:[填充字符][對齊方式][寬度]}# *<20:左對齊,總共20個字符,不夠的用*號填充print('{0:*<20}'.format('hellopython'))# *>20:右對齊,總共20個字符,不夠的用*號填充print('{0:*>20}'.format('hellopython'))# *^20:居中顯示,總共20個字符,不夠的用*號填充print('{0:*^20}'.format('hellopython'))輸出:hellopython******************hellopython****hellopython*****2.位數與進制轉換
#保留2位有效數字print("{:.2f}".format(3.1415926))#轉成二進制print('{0:b}'.format(16))#轉成八進制print('{0:o}'.format(10))#轉成十六進制print('{0:x}'.format(15)) 輸出3.141000012ff-string格式化
在Python 3.6中引入 了f-strings,不僅比str.format使用簡單,而且效率也更高。
使用說明
f-string是字符串前面加上 "f",{}直接使用變量、表達式等。
name='xiaoming'age=12#{}中直接使用變量print(f'My name is {name},My age is {age}')#{}中運行表達式print(f'{1+2+3}')#調用Python內置函數print(f'{name.upper()}')#用lambda匿名函數:可以做復雜的數值計算fun = lambda x : x+1print(f'{fun(age)}')#輸出My name is xiaoming,My age is 126XIAOMING
格式化輸出是python入門最基礎的知識,關于python的學習給大家推薦一個不錯的課程,希望對大家學習有點幫助
總結
以上是生活随笔為你收集整理的python 格式化字符串_Python字符串三种格式化输出的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python中scrapy的middle
- 下一篇: Java hdfs连接池_Java使用连