[python]学习笔记3-字符串内建函数2

来源:互联网 发布:access2010数据库下载 编辑:程序博客网 时间:2024/05/03 18:31


>>> a='hello world'


字符串第一个字母大写


>>> a.capitalize()


'Hello world'


 


以()中指定长度居中显示字符串


>>> a.center(5)


'hello world'


>>> a.center(20)


'   hello world    '


 


统计()内字符串出现次数


>>> a.count('a')


0


>>> a.count('l')


3


>>> 


 


最大字符


>>> c


'Hello World'


>>> max(c)


'r'


>>> a


'hello world'


>>> max(a)


'w'


 


最小字符


>>> min(a)


' '


 


替换字符


>>> d='is a is b is c is d'


>>> d.replace('is','was')


'was a was b was c was d'


>>> d.replace('is','was',3)


'was a was b was c is d'


>>> d.split()


['is', 'a', 'is', 'b', 'is', 'c', 'is','d']


>>> d.split(' ',3)


['is', 'a', 'is', 'b is c is d']


 


按行切分字符串


>>> e='abc\n123\nppt\n\n5566\n'


>>> e


'abc\n123\nppt\n\n5566\n'


>>> print e


abc


123


ppt


 


5566


 


>>> e.splitlines()


['abc', '123', 'ppt', '', '5566']


>>> e.splitlines(0)


['abc', '123', 'ppt', '', '5566']


>>> e.splitlines(2)


['abc\n', '123\n', 'ppt\n', '\n', '5566\n']


>>> e.splitlines(3)


['abc\n', '123\n', 'ppt\n', '\n', '5566\n']


>>> e.splitlines(6)


['abc\n', '123\n', 'ppt\n', '\n', '5566\n']


>>> e.splitlines(9)


['abc\n', '123\n', 'ppt\n', '\n', '5566\n']


>>> 


 


大小写翻转


>>> c


'Hello World'


>>> c.swapcase()


'hELLO wORLD'


>>> e='123erhgFRFGH'


>>> e.swapcase()


'123ERHGfrfgh'


>>> 


 


标题格式输出


>>> a


'hello world'


>>> a.title()


'Hello World'


>>> 


 


查找()内字符所在位置,不存在时返回-1


>>> a.find('d')


10


>>> a.index('d')


10


>>> a.find('z')


-1


 


查找()内字符串所在位置,不存在时抛出异常


>>> a.index('z')


Traceback (most recent call last):


 File "<stdin>", line 1, in <module>


ValueError: substring not found


>>> 


 


istitle判断是否为标题化输出


>>> a='hello world'


>>> a.istitle()


False


>>> b='Hello world'


>>> b.istitle()


False


>>> c='Hello World'


>>> c.istitle()


True


>>> 


 


>>> a


'hello world'


以()中指定长度左对齐显示字符串


>>> a.ljust(0)


'hello world'


>>> a.ljust(28)


'hello world                '


以()中指定长度右对齐显示字符串


>>> a.rjust(28)


'                hello world'


 


以()内字符切分字符串为三部分


>>> a


'hello world'


>>> a.partition('o')


('hell', 'o', ' world')


>>> a.partition(' ')


('hello', ' ', 'world')


>>> a.partition('1')


('hello world', '', '')


>>> a.rpartition('o')


('hello w', 'o', 'rld')


 


以()内指定长度右对齐输出,左侧以0补充


>>> a.zfill(20)


'000000000hello world'


>>> a.zfill(2)


'hello world'



0 0
原创粉丝点击