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