format函数python是什么意思,python的format函数是什么意思
Python2.6 開始,新增了一種格式化字符串的函數 str.format(),它增強了字符串格式化的功能。
基本語法是通過 {} 和 : 來代替以前的 % 。
format 函數可以接受不限個參數,位置可以不按順序。
format格式化函數
實例>>>"{} {}".format("hello", "world") # 不設置指定位置,按默認順序'hello world' >>> "{0} {1}".format("hello", "world") # 設置指定位置'hello world' >>> "{1} {0} {1}".format("hello", "world") # 設置指定位置'world hello world'
也可以設置參數:
相關推薦:《Python視頻教程》
實例#!/usr/bin/python# -*- coding: UTF-8 -*- print("網站名:{name}, 地址 {url}".format(name="龍方網絡", url="www.yzlfxy.com")) # 通過字典設置參數site = {"name": "龍方網絡", "url": "www.yzlfxy.com"}print("網站名:{name}, 地址 {url}".format(**site)) # 通過列表索引設置參數my_list = ['龍方網絡', 'www.yzlfxy.com']print("網站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必須的
輸出結果為:網站名:龍方網絡, 地址 www.yzlfxy.com網站名:龍方網絡, 地址 www.yzlfxy.com 網站名:龍方網絡, 地址 www.yzlfxy.com
也可以向 str.format() 傳入對象:
實例#!/usr/bin/python# -*- coding: UTF-8 -*-class AssignValue(object): def __init__(self, value): self.value = valuemy_value = AssignValue(6)print('value 為: {0.value}'.format(my_value)) # "0" 是可選的
輸出結果為:value 為: 6
數字格式化
下表展示了 str.format() 格式化數字的多種方法:>>> print("{:.2f}".format(3.1415926));3.14
此外我們可以使用大括號 {} 來轉義大括號,如下實例:
實例#!/usr/bin/python# -*- coding: UTF-8 -*- print ("{} 對應的位置是 {{0}}".format("php"))
輸出結果為:
php 對應的位置是 {0}
總結
以上是生活随笔為你收集整理的format函数python是什么意思,python的format函数是什么意思的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php使用redis持久化,redis是
- 下一篇: 廖雪峰Python教程-笔记