国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python中字符串的格式化方法小結(jié)

2020-01-04 17:30:02
字體:
供稿:網(wǎng)友
這篇文章主要介紹了Python中字符串的格式化方法小結(jié),提到了針對(duì)Python2.x與3.x版本相異情況下的不同技巧,需要的朋友可以參考下
 

老辦法

Python2.6之前,格式字符串的使用方法相對(duì)更簡單些,雖然其能夠接收的參數(shù)數(shù)量有限制。這些方法在Python3.3中仍然有效,但已有含蓄的警告稱將完全淘汰這些方法,目前還沒有明確的時(shí)間進(jìn)度表。

格式化浮點(diǎn)數(shù):

pi = 3.14159print(" 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])
 

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 贵州省| 大庆市| 肇州县| 凭祥市| 金湖县| 独山县| 望都县| 陈巴尔虎旗| 阿巴嘎旗| 恩平市| 巨鹿县| 湘阴县| 胶州市| 华池县| 望城县| 泾源县| 沙坪坝区| 安庆市| 天水市| 兴宁市| 东海县| 五大连池市| 如皋市| 随州市| 湘潭县| 上高县| 大埔县| 浮梁县| 泽库县| 沈丘县| 阿尔山市| 牙克石市| 武山县| 青浦区| 雷波县| 渭源县| 犍为县| 商水县| 盘山县| 临夏县| 三门县|