python format函式的使用

2022-06-21 02:18:12 字數 1912 閱讀 6420

**自:

python自2.6後,新增了一種格式化字串函式str.format(),威力十足,可以替換掉原來的%

:以下操作版本是python2.7

通過{} 和 :  替換 %

>>> ' is '.format('jihite', '4 years old')

'jihite is 4 years old'

>>> ' is '.format('jihite', '4 years old')

'jihite is 4 years old jihite'

通過format函式可以接受不限引數個數、不限順序

>>> ':'.format(age=4,name='jihite')

'jihite:4'

>>> ':'.format(age=4,name='jihite',locate='beijing')

'jihite:4'

format括號內用=給變數賦值

>>> class person:

... def __init__(self, name, age):

... self.name,self.age = name, age

... def __func__(self):

... return "this guy is , is old".format(self=self)

...

>>> s =person('jihite', 4)

>>> s.__func__()

'this guy is jihite, is 4 old'

>>> ' is  years old!'.format(['jihite', 4])

'jihite is 4 years old!'

>>> ' is years old!'.format('jihite', 4)

'jihite is 4 years old!'

其實就是通過位置

通過{} : 符號

^<>分別表示居中、左對齊、右對齊,後面帶寬度

>>> ''.format('jihite')

' jihite'

>>> ''.format('jihite')

'jihite '

>>> ''.format('jihite')

' jihite '

精度常和f一起使用

>>> ''.format(3.1415)

'3.14'

>>> ''.format(3.1)

'3.1000'

>>> ''.format(10)

'1010'

>>> ''.format(10)

'12'

>>> ''.format(10)

'10'

>>> ''.format(10)

'a'

其中b o d x分別表示

二、八、十、十六進製制

>>> ''.format(1000000)

'1,000,000'

>>> ''.format(100000.23433)

'100,000.23433'

>>> ''.format('abcedef')

traceback (most recent call last):

file "", line 1, in valueerror: cannot specify ',' with 's'.

尤其是其中的精度與型別,用起來很方便

Python format函式詳解

python從2.6開始支援format,新的更加容易讀懂的字串格式化方法,從原來的 模式變成新的可讀性更強的 花括號宣告 用於渲染前的引數引用宣告,花括號裡可以用數字代表引用引數的序號,或者 變數名直接引用。從format引數引入的變數名 冒號 字元位數宣告 空白自動填補符 的宣告 千分位的宣告 ...

Python format函式使用

format函式是一種格式化輸出字串的函式 str.format 基本語法是通過 和 來代替以前的 中可以填寫後面元組中的下標 也可以填寫後面的欄位名 需要知道替換字元的型別,format則不需要 a hello b 小明 小明 age 18,男 adress 上海 用逗號還能做金額的千位分隔符 控...

python format函式使用

format是乙個格式化字串的方法 簡單理解就是把format s1,s2,去替換前面的 舉個例子 city 昆明 province 雲南 print 的省會是 format province,city 輸出 雲南的省會是 昆明 上面的例子是依次按順序填充,第乙個 被替換成format 裡面的第乙個...