python学习之Strings

来源:互联网 发布:python算法教程 pdf 编辑:程序博客网 时间:2024/06/06 16:31

join and split

>>> #join 连接字符串>>> one = ['Hello','My','name','is','Marry']>>> ' '.join(one)'Hello My name is Marry'>>> '_'.join(one)'Hello_My_name_is_Marry'>>> '...'.join(one)'Hello...My...name...is...Marry'>>> one['Hello', 'My', 'name', 'is', 'Marry']>>> two = '***'.join(one)>>> two'Hello***My***name***is***Marry'>>> #split 拆分字符串>>> two.split()['Hello***My***name***is***Marry']>>> two.split('***')['Hello', 'My', 'name', 'is', 'Marry']>>> two.split('***',0)['Hello***My***name***is***Marry']>>> two.split('***',1)['Hello', 'My***name***is***Marry']>>> two.split('***',2)['Hello', 'My', 'name***is***Marry']>>> two.split('***',3)['Hello', 'My', 'name', 'is***Marry']>>> two.split('***',-1)['Hello', 'My', 'name', 'is', 'Marry']>>> s = 'hello python'>>> l = list(s)>>> l['h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o', 'n']>>> ''.join(l)'hello python'

% or format

>>> #format在这里更灵活>>> '%s,eggs,and %s'%('spam','SPAM')'spam,eggs,and SPAM'>>> '{0},eggs,and {1}'.format('spam','SPAM')'spam,eggs,and SPAM'>>> '{1},eggs,and {0}'.format('spam','SPAM')'SPAM,eggs,and spam'>>> '{},eggs,and {}'.format('spam','SPAM')'spam,eggs,and SPAM'>>> #format和%实现效果一致>>> '{:.2f}'.format(3.1415926535)'3.14'>>> '%.2f'%(3.1415926535)'3.14'>>> '{:.5f}'.format(3.1415926535)'3.14159'>>> '%.5f'%(3.1415926535)'3.14159'>>> '{:5d}'.format(42)'   42'>>> '%5d'%(42)'   42'>>> #这里终于有区别了,但是format如何实现左对齐呢?>>> '{:-5d}'.format(-42)'  -42'>>> '%-5d'%(-42) '-42  '>>> #%应该实现不了这个格式>>> '{:,}'.format(123456789)'123,456,789'
原创粉丝点击