python中format函數(shù)如何使用
Python2.6 開始,新增了一種格式化字符串的函數(shù) str.format(),它增強(qiáng)了字符串格式化的功能。
基本語法是通過 {} 和 : 來代替以前的 % 。
format 函數(shù)可以接受不限個(gè)參數(shù),位置可以不按順序。
例如
>>>'{} {}'.format('hello', 'world') # 不設(shè)置指定位置,按默認(rèn)順序’hello world’>>> '{0} {1}'.format('hello', 'world') # 設(shè)置指定位置’hello world’>>> '{1} {0} {1}'.format('hello', 'world') # 設(shè)置指定位置’world hello world’
也可設(shè)置參數(shù)
#!/usr/bin/python# -*- coding: UTF-8 -*-print('網(wǎng)站名:{name}, 地址 {url}'.format(name='python學(xué)習(xí)網(wǎng)', url='www.py.cn'))# 通過字典設(shè)置參數(shù)site = {'name': 'python學(xué)習(xí)網(wǎng)', 'url': 'www.py.cn'}print('網(wǎng)站名:{name}, 地址 {url}'.format(**site))# 通過列表索引設(shè)置參數(shù)my_list = [’好吧啦網(wǎng)’, ’www.jb51.net’]print('網(wǎng)站名:{0[0]}, 地址 {0[1]}'.format(my_list)) # '0' 是必須的
輸出結(jié)果
網(wǎng)站名:好吧啦網(wǎng), 地址 www.jb51.net網(wǎng)站名:好吧啦網(wǎng), 地址 www.jb51.net網(wǎng)站名:好吧啦網(wǎng), 地址 www.jb51.net
到此這篇關(guān)于python中format函數(shù)如何使用的文章就介紹到這了,更多相關(guān)python的format函數(shù)用法內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
