Python format 格式化函式

2022-09-08 05:18:12 字數 1291 閱讀 1038

str.format()

格式化字串的函式 str.format(),它增強了字串格式化的功能。

基本語法是通過 {} 和 : 來代替以前的 % 

format 函式可以接受不限個引數,位置可以不按順序。

1 >>>"

{} {}

".format("

hello

", "

world

") #

不設定指定位置,按預設順序2'

hello world'3

4 >>> "

".format("

hello

", "

world

") #

設定指定位置5'

hello world'6

7 >>> "

".format("

hello

", "

world

") #

設定指定位置8'

world hello world

'

也可以設定關鍵字:

#

!/usr/bin/python

#-*- coding: utf-8 -*-

print("

".format(name="

菜鳥教程

", url="

www.runoob.com"))

#通過字典設定引數

site =

print("

".format(**site)) #

通過列表索引設定引數

my_list = ['

菜鳥教程

', '

www.runoob.com']

print("

".format(my_list)) #

"0" 是必須的

也可以向str.format()傳入物件

#

!/usr/bin/python

#-*- coding: utf-8 -*-

class

assignvalue(object):

def__init__

(self, value):

self.value =value

my_value = assignvalue(6)

print('

value 為:

'.format(my_value)) #

"0" 是可選的

數字格式化

-----待補充

Python format 格式化函式

數字 格式輸出 描述3.1415926 3.14 保留小數點後兩位 3.1415926 3.14 帶符號保留小數點後兩位 1 1.00 帶符號保留小數點後兩位 2.71828 3不帶小數505 數字補零 填充左邊,寬度為2 55 數字補x 填充右邊,寬度為4 1010xx 數字補x 填充右邊,寬度為...

Python format 格式化函式

python2.6 開始,新增了一種格式化字串的函式 str.format 它增強了字串格式化的功能。基本語法是通過 和 來代替以前的 format 函式可以接受不限個引數,位置可以不按順序。不設定指定位置,按預設順序 print format hello world 設定指定位置 print fo...

Python format 格式化函式

python2.6 開始,新增了一種格式化字串的函式 str.format 它增強了字串格式化的功能。栗子 name 雷歐 age 28 add m78星雲 print 你好,我叫 我來自 今年 歲.format name,add,age print 你好,我叫 name 我來自 add 今年 ag...