欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python中format函數(shù)如何使用

 更新時(shí)間:2020年06月22日 10:23:42   作者:silencement  
在本篇內(nèi)容里小編給大家整理的是一篇關(guān)于python的format函數(shù)用法以及相關(guān)實(shí)例,需要的朋友們學(xué)習(xí)下。

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 = ['腳本之家', 'www.dbjr.com.cn']
print("網(wǎng)站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必須的

輸出結(jié)果

網(wǎng)站名:腳本之家, 地址 www.dbjr.com.cn
網(wǎng)站名:腳本之家, 地址 www.dbjr.com.cn
網(wǎng)站名:腳本之家, 地址 www.dbjr.com.cn

到此這篇關(guān)于python中format函數(shù)如何使用的文章就介紹到這了,更多相關(guān)python的format函數(shù)用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論