54、1-字符串格式化
2019-05-28 本文已影响3人
BeautifulSoulpy
任何不能把我打倒的,终将使我变强大。

字符串本质就是一个数组,不过是拿字符存进去的
统一使用Unicode类型;
python只有 【字符串】 类型,没有其他复杂的数据类型;
所有这些方法,知道在上面场景下用什么方法,没有必要去死背;
1.字符串定义初始化
s1='string'
s2='string2'
s3='''this a "String"'''
s4='hello \n magedu.com'
s5=r"hello \n magedu.com" #所有的字符串都是直接按照字面的意思来打印;
s6='c:\windows\nt'
s7=R'c:\windows\nt'
s8='c:windows\\nt'
sql="""select * from user where name='tom'"""
2.C风格打印(%)与Python风格打印 (format);
%为C风格打印,推荐使用比较方便的 format函数();python2.7中有很多特性已经加入到python3中去了;

format 函数 " {}{xxx}".format(args,*kwargs) ->str
新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。相对于老版的%格式方法,它有很多优点。
1.在%方法中%s只能替代字符串类型,而在format中不需要理会数据类型;
2.单个参数可以多次输出,参数顺序可以不相同;
3.填充方式十分灵活,对齐方式十分强大;
4.官方推荐用的方式,%方式将会在后面的版本被淘汰。
^1 Useage使用
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 !
^2 数字格式化
数字 格式 输出 描述
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)
^3 进制转换
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 分别是二进制、十进制、八进制、十六进制。
^4 输出大括号
print("{} {{0}}".format("opcai_linux"))
opcai_linux {0}
#format 函数 总结
对齐、填充输出:
< 靠左对齐
> 靠右对齐
^ 中间对齐(异或符)
{:^*长度}
中间对齐,指定长度输出,不足以*补齐
# "{}{xxx}".format(*args,**kwargs) ->str
"The sum of 1+2 is {0}".format(1+2)
"{:>10}".format(97) | ' 97'
"{:>10b}".format(97) | ' 1100001'
3. 函数总结
前包后不包:【) #大多都是前包后不包;
前后都包:【】 #只有少数2个函数 randomint、