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)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Spring Boot和Thymeleaf整合結(jié)合JPA實(shí)現(xiàn)分頁效果(實(shí)例代碼)2. 詳解Android studio 動(dòng)態(tài)fragment的用法3. 什么是python的自省4. 解決Android studio xml界面無法預(yù)覽問題5. Springboot Druid 自定義加密數(shù)據(jù)庫(kù)密碼的幾種方案6. Vuex localStorage的具體使用7. php模擬實(shí)現(xiàn)斗地主發(fā)牌8. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)9. Spring MVC+ajax進(jìn)行信息驗(yàn)證的方法10. vue 使用localstorage實(shí)現(xiàn)面包屑的操作

網(wǎng)公網(wǎng)安備