Format函式的一些用法

2022-04-30 02:12:08 字數 2169 閱讀 3384

format格式化字串

1.按序傳入引數

實際上format()裡面的會包裝成為乙個元組,若「」裡面的{}裡沒有具體的引數,則按照順序填入

print("

my name is {}, my age is {}, my hobby is {}

".format("

alex

", 18, "

pingpangball

"))

結果:my name isalex, my age is 18, my hobby is pingpangball

2.按照{}裡面的引數傳入

print("

my name is , my age is , my hobby is

".format("

alex

", 18, "

pingpangball"))

print("

my name is , my age is , my hobby is

".format("

alex

", 18, "

pingpangball"))

print("

my name is , my age is , my hobby is

".format("

alex

", 18, "

pingpangball

"))

結果:my name is alex, my age is 18, my hobby ispingpangball

my name is pingpangball, my age is 18, my hobby isalex

my name is 18, my age is alex, my hobby ispingpangball

3.按照鍵值對來將值傳入

print("

my name is , my age is , my hobby is

".format(name = "

alex

", age = 18, hobby = "

pingpangball"))

print("

my name is , my age is , my hobby is

".format(age = 18, hobby = "

pingpangball

", name = "

alex

"))

結果:my name is alex, my age is 18, my hobby ispingpangball

my name is alex, my age is 18, my hobby ispingpangball

4.指定傳入的值的資料型別

print("

s1 = , s2 = , s3 = , s4 = , s5 = , s6 =

".format(12, 13, 14, 15, 16, 17))

結果:s1 = 12, s2 = 13.000000, s3 = 1110, s4 = 1.500000e+01, s5 = 20, s6 = 11

5.多括號的情形

print("

my name is

".format("

alex"))

print("

my name is }

".format("

alex"))

print("

my name is }}

".format("

alex"))

print("

my name is }}}

".format("

alex"))

print("

my name is }}}}

".format("

alex

"))

結果:my name is alex

my name is

my name is

my name is }

my name is }

分析:由於}可以轉義為{},因此導致上述結果,也能直接看出來format()裡面的引數不一定會傳給前方字串中

Format函式的用法

format函式的用法總結如下 函式宣告 function format const format string const args array of const string overload 函式功能 事實上format方法有兩個種形式,另外一種是三個引數的,主要區別在於它是執行緒安全的,但並...

SQLite一些函式用法

格林威治日期時間,比北京時間晚8小時 select datetime now 格林威治日期 select date now 本地時間 select time now localtime 日期時間格式化 select strftime y m d h m s now localtime 加1小時 se...

MDX函式的一些用法

mdx的函式使用 paralleperiod 同期 例子 paralleperiod time yqmd year 1,time yqmd currentmember 與去年同期 periodtodate 本年至今 例子 periodtodate time yqmd year time yqmd c...