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

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

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

 format()函數(shù)

"""
測試 format()函數(shù)
"""
def testFormat():
  # format()函數(shù)中有幾個元素,前面格式化的字符串中就要有幾個 '{}'
  # 位置
  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)
  # 索引可以重復使用
  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ù)中元素個數(shù),和前面的字符串中的'{}'個數(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個數(shù),索引是5')
  print('其他用法:')
  print(s4)
  print(s5)
  print('-' * 8)
  return
if __name__ == '__main__':
  testFormat()

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

用法:

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

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

要點:從以下例子可以看出位置參數(shù)不受順序約束,且可以為{},只要format里有相對應的參數(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、使用關鍵字參數(shù)

要點:關鍵字參數(shù)值要對得上,可用字典當關鍵字參數(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、填充與格式化

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

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

4、精度與進制

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

5、使用索引

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

總結

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

相關文章

最新評論