[python] 字符串格式化

1、按照默認順序,不指定位置

print("{} {}".format("hello","world") )

hello world

 

2、設置指定位置,可以多次使用

print("{0} {1} {0}".format("hello","or"))

hello or hello

 

3、使用列表格式化

person = {"name":"opcai","age":20}

print("My name is {name} . I am {age} years old .".format(**person))

My name is opcai . I am 20 years old .

 

4、通過列表格式化

stu = ["opcai","linux","MySQL","Python"]

print("My name is {0[0]} , I love {0[1]} !".format(stu))

My name is opcai , I love linux !


數字格式輸出 

3.1415926 {:.2f} 3.14 保留小數點後兩位

3.1415926 {:+.2f} +3.14 帶符號保留小數點後兩位

-1 {:+.2f} -1.00 帶符號保留小數點後兩位

2.71828 {:.0f} 3 不帶小數

5 {:0>2d} 05 數字補零 (填充左邊, 寬度爲2)

5 {:x<4d} 5xxx 數字補x (填充右邊, 寬度爲4)

10 {:x<4d} 10xx 數字補x (填充右邊, 寬度爲4)

1000000 {:,} 1,000,000 以逗號分隔的數字格式

0.25 {:.2%} 25.00% 百分比格式

1000000000 {:.2e} 1.00e+09 指數記法

13 {:10d} 13 右對齊 (默認, 寬度爲10)

13 {:<10d} 13 左對齊 (寬度爲10)

13 {:^10d} 13 中間對齊 (寬度爲10)

 

 

進制轉換

11 '{:b}'.format(11) 1011 二進制

11 '{:d}'.format(11) 11 十進制

11 '{:o}'.format(11) 13 八進制

11 '{:x}'.format(11) b 十六進制

11 '{:#x}'.format(11) 0xb 十六進制

11 '{:#X}'.format(11) 0XB 十六進制

 

 

^, <, > 分別是居中、左對齊、右對齊,後面帶寬度, : 號後面帶填充的字符,只能是一個字符,不指定則默認是用空格填充。

+ 表示在正數前顯示 +,負數前顯示 -; (空格)表示在正數前加空格

b、d、o、x 分別是二進制、十進制、八進制、十六進制。

 

 

輸出大括號

print("{} {{0}}".format("opcai_linux"))

opcai_linux {0}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章