Python中的字符串操作(Python3.6.1版本)
(1)切片操作:
''(左闭右开:即是从1到2)
''
''
'hello world!'
>>> str='hello world!'>>> str.capitalize ()'ello world!'>>>
(4)casefold():将整个字符串小写
>>> str1="Hello world!">>> str1.casefold ()'ello world!'>>>
(5)center(width):将整个字符串居中(如果不够width则用空格补充)
str1="Hello world!"
>>> str1.center(20)' Hello world! '>>>
(6)count(sub[,start[,end]]):sub从start到end出现的次数(默认是整个字符串)
str1="Hello world!"
>>> str1.count ('l',3)2("Hello word!")>>> str1.count ('l')3("Heo world!")>>> str1.count('l',3,6)1("Hello word!")>>>
str1="Hello world!"
>>> str1.endswith('orld!')True("Hello w")>>>
>>> str2='include world!'>>> str2.expandtabs()'include world!'>>>
str1="Hello world!"
>>> str1.find('llo')2("He world!")>>> str1.find('llo',8)-1>>>
str1="Hello world!"
>>> str1.isalnum()False("Hello world!")>>>
>>> str=" ">>> str.isspace()True>>>
>>> str="12345dfgbhn">>> str.isdigit()False("12345dfgbhn")>>>
>>> str='asdfghj'>>> str.isalpha()True>>>
>>> str='asdfghj'>>> str.islower()True>>>
(15)istitle():判断是否是标题形式字符串(即是连续字符串只有第一个字母大写,其他都是小写,若是有空格,则每个分隔的字符串都满足此)
>>> str='Helloworld'>>> str.istitle()True>>>
>>> str='HELLO WOLD'>>> str.isupper()True>>>
>>> str1="abc">>> str1.join('1234')'12abc34'>>>
>>> str=" hello world!">>> str.lstrip()'hello world!'>>>
>>> str="hello world! ">>> str.rstrip()'hello world!'>>>
str='hello world!'
>>> str.replace('hello','HELLO',2)' world! '>>>
>>> str="hello world!">>> str.rfind('d!',5)-1>>> str.rfind('d!')10>>>
(22)split(sep):将字符串用给定的标准分割,并且以列表形式返回分割后的元素组
>>> str="1,2,4">>> str.split(',')['1','2','3','4']>>>
>>> str.startswith('hel')True>>>
>>> str=' hello world! '>>> str.strip()'hello world!'>>>
(25)swapcase():将字符串的大小写反转
>>> str="Hello world!">>> str.swapcase ()'ELLO WORLD!'>>>
>>> str="hello world!">>> str.title()'ello orld!'>>>
(27)translate(table)
>>> str="sssaabb">>> str.translate(str.maketrans('s','b'))'bbbaabb'>>>
(28)upper():将整个字符串都大写
>>> str="hello world!">>> str.upper()'HELLO WORLD!'>>>
(29)zfill(width):用'0'来填充不够的空格(是从左边开始填充)
>>> str="hello world! ">>> str.zfill(20)'00000hello world! '>>>
(30)lower():将整个字符串都小写
>>> str="HELLO worldQ">>> str.lower()' worldq'>>>
>>> '{0} love {1}{2}'.format('I','my','home')'I love myhome'>>> '{0} love {1} {2}'.format('I','home')'I love my home'>>> '{a} love {b} {c}'.format(a='I',b='my',c='home')'I love my home'
>>> '{0:.1f}{1}'.format(27.658,'GB')'27.7GB'>>>
>>> "%d+%d=%d" % (4,5,4+5)'4+5=9'>>>
>>> '%c' % 97'a'>>>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。