加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python中的字符串操作总结(Python3.6.1版本)

发布时间:2020-12-17 00:04:27 所属栏目:Python 来源:网络整理
导读:Python中的字符串操作(Python3.6.1版本) (1)切片操作: ' '(左闭右开:即是从1到2) ' ' ' ' 'h ello world!' >>> str='hello world!'>>> str.capitalize ()' ello world!'>>> (4)casefold():将整个字符串小写 >>> str1="Hello world!">> str1.casef

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'>>>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读