欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

淺析python3字符串格式化format()函數(shù)的簡單用法

 更新時(shí)間:2018年12月07日 10:22:04   作者:踏破凌霄城  
這篇文章主要介紹了python3字符串格式化format()函數(shù)的簡單用法,代碼簡單易懂,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

 format()函數(shù)

"""
測(cè)試 format()函數(shù)
"""
def testFormat():
  # format()函數(shù)中有幾個(gè)元素,前面格式化的字符串中就要有幾個(gè) '{}'
  # 位置
  s1 = 'a{}b{}c{}d{}'.format(1, 2, 3, 4)
  # 索引,format()函數(shù)中的元素,從0開始
  s2 = 'a{0}b{1}c{3}d{2}'.format(1, 2, 3, 4)
  # 索引可以重復(fù)使用
  s3 = 'a{0}b{1}c{0}d{1}'.format(1, 2, 3, 4)
  print('-' * 8)
  print('一般用法:')
  print(s1)
  print(s2)
  print(s3)
  print('-' * 8)
  # format()函數(shù)中元素個(gè)數(shù),和前面的字符串中的'{}'個(gè)數(shù)不相同
  # 格式化字符串中的'{}'里面必須要有后面format()函數(shù)中元素的索引
  s4 = 'a{0}b{1}cd'.format(1, 2, 3, 4)
  s5 = 'a{0}b{1}c{0}d{1}e{1}f{1}g{1}h{1}{4}{4}{4}{4}{5}{4}{4}{4}{4}'.format(1, 2, 3, 4, '*', '哈哈,這是第6個(gè)數(shù),索引是5')
  print('其他用法:')
  print(s4)
  print(s5)
  print('-' * 8)
  return
if __name__ == '__main__':
  testFormat()

ps:下面看下python3字符串格式化(format)

用法:

  它通過{}和:來代替?zhèn)鹘y(tǒng)%方式

1、使用位置參數(shù)

要點(diǎn):從以下例子可以看出位置參數(shù)不受順序約束,且可以為{},只要format里有相對(duì)應(yīng)的參數(shù)值即可,參數(shù)索引從0開,傳入位置參數(shù)列表可用*列表

 >>> li = ['hoho',]
 >>> 'my name is {} ,age {}'.format('hoho',)
 'my name is hoho ,age '
 >>> 'my name is {} ,age {}'.format(,'hoho')
 'my name is hoho ,age '
 >>> 'my name is {} ,age {} {}'.format(,'hoho')
 'my name is hoho ,age hoho'
 >>> 'my name is {} ,age {}'.format(*li)
 'my name is hoho ,age '

2、使用關(guān)鍵字參數(shù)

要點(diǎn):關(guān)鍵字參數(shù)值要對(duì)得上,可用字典當(dāng)關(guān)鍵字參數(shù)傳入值,字典前加**即可

 >>> hash = {'name':'hoho','age':}
 >>> 'my name is {name},age is {age}'.format(name='hoho',age=)
 'my name is hoho,age is '
 >>> 'my name is {name},age is {age}'.format(**hash)
 'my name is hoho,age is 18'

3、填充與格式化

:[填充字符][對(duì)齊方式 <^>][寬度]

 >>> '{:*>}'.format() ##右對(duì)齊
 '********'
 >>> '{:*<}'.format() ##左對(duì)齊
 '********'
 >>> '{:*^}'.format() ##居中對(duì)齊
6 '****10****'

4、精度與進(jìn)制

 >>> '{:.f}'.format(/)
 '.'
 >>> '{:b}'.format()  #二進(jìn)制
 ''
 >>> '{:o}'.format()   #八進(jìn)制
 ''
 >>> '{:x}'.format()   #進(jìn)制
 'a'
 >>> '{:,}'.format() #千分位格式化
 ',,,'

5、使用索引

 >>> li
 ['hoho', ]
 >>> 'name is {[]} age is {[]}'.format(li)
 'name is hoho age is 

總結(jié)

以上所述是小編給大家介紹的python3字符串格式化format()函數(shù)的簡單用法,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評(píng)論