Python常见字符串处理操作

Python中字符串处理的方法已经超过37种了,下面是一些常用的字符串处理的方法,以后慢慢添加。

>>> s = 'Django is cool' #创建一个字符串
>>> words = s.split()   #使用空格分隔字符串,保存在一个words列表里
>>> words
['Django', 'is', 'cool']
>>> ' '.join(words)    #用空格重组字符串
'Django is cool'
>>> '::'.join(words)   #用::重组字符串
'Django::is::cool'
>>> ''.join(words)     #直接重组字符串
'Djangoiscool'
>>> s.upper()          #将字符串改为大写
'DJANGO IS COOL'
>>> s.title()      #将字符串中的每个词的首字母变为大写
'Django Is Cool'
>>> s.upper().isupper()   #判断字符串是否为大写
True
>>> s.capitalize()     #将字符串的首字母变为大写
'Django is cool'
>>> s 'Django is cool' >>> s.lower().title() 'Django Is Cool' >>> s.lower() 'django is cool' >>> s.lower().capitalize() 'Django is cool'

>>> s.count('o')    #计算字符串中某个字符的数目 3 >>> s.find('go')    #从字符串中查找某个字符串,查找成功后返回该字符串的下标 4 >>> >>> s.find('xxx') #查找字符串,失败后返回-1 -1 >>> s.startswith('Python')  #判断是否为字符串的起始字符串,是返回true,不是则返回false False >>> s.startswith('Django') True >>> s.replace('Django','Python') #字符串替换 'Python is cool'

 

posted @ 2016-04-26 15:58  sunny_2015  阅读(482)  评论(0编辑  收藏  举报