最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python中字符串的格式化方法小結

 更新時間:2016年05月03日 17:49:14   作者:larry  
這篇文章主要介紹了Python中字符串的格式化方法小結,提到了針對Python2.x與3.x版本相異情況下的不同技巧,需要的朋友可以參考下

老辦法

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

格式化浮點數:

pi = 3.14159
print(" pi = %1.2f ", % pi)


多個替換值:

s1 = "cats"
s2 = "dogs"
s3 = " %s and %s living together" % (s1, s2)

沒有足夠的參數:

使用老的格式化方法,我經常犯錯"TypeError: not enough arguments for formating string",因為我數錯了替換變量的數量,編寫如下這樣的代碼很容易漏掉變量。

set = (%s, %s, %s, %s, %s, %s, %s, %s) " % (a,b,c,d,e,f,g,h,i)

對于新的Python格式字符串,可以使用編號的參數,這樣你就不需要統(tǒng)計有多少個參數。

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])

相關文章

最新評論

浏阳市| 南开区| 米林县| 丘北县| 易门县| 汾西县| 崇左市| 繁峙县| 黄山市| 鄂托克旗| 应用必备| 星子县| 衡山县| 江口县| 上饶县| 灯塔市| 太谷县| 灵璧县| 酒泉市| 合水县| 长治市| 广灵县| 绵竹市| 伊金霍洛旗| 莱州市| 措勤县| 东城区| 樟树市| 马尔康县| 宜丰县| 兴隆县| 绥阳县| 丹棱县| 浦县| 三原县| 宝山区| 司法| 丰顺县| 昆山市| 新巴尔虎右旗| 乌苏市|