format()函數
""" 測試 format()函數 """ def testFormat(): # format()函數中有幾個元素,前面格式化的字符串中就要有幾個 '{}' # 位置 s1 = 'a{}b{}c{}d{}'.format(1, 2, 3, 4) # 索引,format()函數中的元素,從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()函數中元素個數,和前面的字符串中的'{}'個數不相同 # 格式化字符串中的'{}'里面必須要有后面format()函數中元素的索引 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個數,索引是5') print('其他用法:') print(s4) print(s5) print('-' * 8) return if __name__ == '__main__': testFormat()