Python中字符串的格式化方法小結(jié)
老辦法
Python2.6之前,格式字符串的使用方法相對(duì)更簡(jiǎn)單些,雖然其能夠接收的參數(shù)數(shù)量有限制。這些方法在Python3.3中仍然有效,但已有含蓄的警告稱將完全淘汰這些方法,目前還沒有明確的時(shí)間進(jìn)度表。
格式化浮點(diǎn)數(shù):
pi = 3.14159 print(" pi = %1.2f ", % pi)
多個(gè)替換值:
s1 = "cats" s2 = "dogs" s3 = " %s and %s living together" % (s1, s2)
沒有足夠的參數(shù):
使用老的格式化方法,我經(jīng)常犯錯(cuò)"TypeError: not enough arguments for formating string",因?yàn)槲覕?shù)錯(cuò)了替換變量的數(shù)量,編寫如下這樣的代碼很容易漏掉變量。
set = (%s, %s, %s, %s, %s, %s, %s, %s) " % (a,b,c,d,e,f,g,h,i)
對(duì)于新的Python格式字符串,可以使用編號(hào)的參數(shù),這樣你就不需要統(tǒng)計(jì)有多少個(gè)參數(shù)。
set = set = " ({0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}) ".format(a,b,c,d,e,f,g)
Python 2.x 基于字典字符串格式化
"%(n)d %(x)s" %{"n":1, "x":"spam"} reply = """ Greetings... Hello %(name)s! Your age squared is %(age)s """ values = {'name':'Bob', 'age':40} print rely % values
Python 3.x format方法格式化
template = '{0},{1} and {2}' template.format('spam','ham','eggs') template = '{motto}, {pork} and {food}' template.format(motto='spam', pork='ham', food='eggs') template = '{motto}, {0} and {food}' template.format('ham', motto='spam', food='eggs') '{motto}, {0} and {food}'.format(42, motto=3.14, food=[1,2,3])
- 淺談Python 字符串格式化輸出(format/printf)
- Python字符串格式化輸出方法分析
- Python中用format函數(shù)格式化字符串的用法
- python 字符串格式化代碼
- Python3.x版本中新的字符串格式化方法
- python格式化字符串實(shí)例總結(jié)
- Python常見格式化字符串方法小結(jié)【百分號(hào)與format方法】
- Python中字符串格式化str.format的詳細(xì)介紹
- Python實(shí)現(xiàn)字符串格式化的方法小結(jié)
- Python實(shí)現(xiàn)字符串逆序輸出功能示例
- Python實(shí)現(xiàn)字符串格式化輸出的方法詳解
相關(guān)文章
Python多進(jìn)程并發(fā)與多線程并發(fā)編程實(shí)例總結(jié)
這篇文章主要介紹了Python多進(jìn)程并發(fā)與多線程并發(fā)編程,結(jié)合實(shí)例形式總結(jié)分析了Python編程中的多進(jìn)程并發(fā)與多線程并發(fā)相關(guān)概念、使用方法與操作注意事項(xiàng),需要的朋友可以參考下2018-02-02python socket模塊創(chuàng)建和使用套接字示例詳解
這篇文章主要為大家介紹了python socket模塊來創(chuàng)建和使用套接字示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06pandas pd.read_csv()函數(shù)中parse_dates()參數(shù)的用法說明
這篇文章主要介紹了pandas pd.read_csv()函數(shù)中parse_dates()參數(shù)的用法說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-03-03Python3 socket即時(shí)通訊腳本實(shí)現(xiàn)代碼實(shí)例(threading多線程)
這篇文章主要介紹了Python3 socket即時(shí)通訊腳本實(shí)現(xiàn)代碼實(shí)例(threading多線程),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06python daemon守護(hù)進(jìn)程實(shí)現(xiàn)
這篇文章主要介紹了python daemon守護(hù)進(jìn)程實(shí)現(xiàn),需要的朋友可以參考下2016-08-08