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