[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}

发布了89 篇原创文章 · 获赞 17 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/lbt_dvshare/article/details/103432680