python的字符串模块很强大,有很多内置的方法,我们介绍下常用的字符串方法:
一. find和rfind方法查找字串所在位置
s = 'abcdef' print s.find('def') print s.find('defg') print s.rfind('def') print s.rfind('defg')
find和rfind如果有结果将返回大于等于0的结果,无结果则返回-1;另外index方法也可以返回子字符串的位置,但是如果找不到会抛出异常
二. 从字符串中截取子字符串
python 中没有substr或者substring的方法,但是可以通过数组slice的方法,方便的截取子字符串
s = 'abcdefg' print s[3,4]
三. 判断字符串是否包含某个字串
s = 'abcdef' print 'bcd' in s
将输出True
四. 获得字符串的长度
在python中获得任何集合的长度都可以使用len方法
s = 'abc' print len(s)
五. python的字符串大小写转换
s = 'abcDef' print s.lower() print s.upper() print s.capitalize()
将输出
abcdef ABCDEF Abcdef
六. count查看子字符串出现的次数
s = 'abcdabcdab' print s.count('abcd')
将输出2