九.格式化
格式化字符串(通过center,ljust,rjust方法做居中,左对齐和右对齐的处理,在字符串左侧补零,使用zfill方法。)
s='hello,world'
#center方法以宽度20将字符串居中并在两侧填充*
print(s.center(20,'*') )
运行后:
#****hello,world****
(123456789...........)
#rjust方法以宽度20将字符串右对齐并在左侧填充空格.
print(s.rjust(20) )
运行后:
# hello,world
123456789...... .....
#ljust方法以宽度20将字符串左对齐并在右侧填充~
print(s.ljust(20,'~') )
运行后:
#hello,world~~~~~~~~
#在字符串左侧补0
print('33',zfill(5))
运行后:
#00033
print('-33',zfill(5))
运行后:
#-0033
print函数输出字符串
a=321 b=123 print('%d*%d=%d'%(a,b,a*b)
运行后: #321*123=39483
字符串的方法
a=321 b=123 print('{0}*{1}={2}'.format(a,b,a*b)
运行后: #321*123=39483
如需进一步控制格式化变量值形式,参考以下:
变量值 | 占位符 | 格式化结果 | 说明 |
3.1415926 | {:.2f} | '3.14' | 保留小数点后两位 |
3.1415926 | {:+.2f} | '+3.14' | 带符号保留小数点后两位 |
-1 | {:+.2f} | '-1.00' | 带符号保留小数点后两位 |
3.1415926 | {:.0f} | '3' | 不带小数 |
123 | {:0>10d} | '0000000123' | 左边补0,补够十位 |
123 | {:x<10d} | '123xxxxxxx' | 右边补x,补够十位 |
123 | {: >10d} | ' 123' | 左边补空格,补够十位 |
123 | {: <10} | '123 ' | 右边补空格,补够十位 |
123456789 | {:, } | '123,456,789' | 逗号分隔格式 |
0.123 | {:.2%} | '12.30%' | 百分比格式 |
123456789 | {:.2e} | '1.23e+08' | 科学计数法格式 |
修剪操作(将原字符串修剪掉左右两端空格之后的字符串)
S=' tuling_python@126.com /t/r/n' #strip方法获得字符串修剪左右两侧空格之后的字符串 print(s.strip() ) 运行后: #tuling_python@126.com
替换操作:replace
S='hello,world' print(s.replace('o','@')) 运行后: #hell@,w@rld print(s.replace('o','@',1)) 运行后: #hell@,world
拆分/合并操作 split(默认空格进行拆分)
S='I love you' words=s.split() print(words) 运行后: #['I','love','you'] print('#'.join(words)) 运行后: #I#love#you
不默认空格,指定其他字符拆分
S='I#love#you#so#much' words=s.split('#') print(words) 运行后: #['I','love','you','so','much'] words=s.split('#',3) print(words) 运行后: #['I','love','you','so#much']
十.集合
常用数据结构之集合(set)
集合定义:把一定