字符串常用方法:
- name = 'xiaoming.li'
- print(name.count('i')) #找某个元素出现的次数
- print(name.index('o')) #找下标
3 Python split() 通过指定分隔符对字符串进行切片, 如果参数 num 有指定值, 则分隔 num+1 个子字符串, 注意: 默认为所有的空字符, 包括空格, 换行 (\n), 制表符(\t) 等.
- tr = "Line1-abcdef \nLine2-abc \nLine4-abcd";
- print str.split(); # 以空格为分隔符, 包含 \n
- print str.split(' ', 1 ); # 以空格为分隔符, 分隔成两个
结果:
- ['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
- ['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
4 python strip()方法用于移除字符串头尾指定的字符 (默认为空格或换行符) 或字符序列, 注意: 该方法只能删除开头或者结尾的字符, 不能删除删除中间部分 的字符:
4.1 去除首尾字符:
- str1 = "00003210Runoob012300000";
- print(str1.strip('0'));# 去除首尾字符 0
结果: 3210Runoob0123
- str2 = "Runoob"; #去除首位空格
- print(str2.strip())
结果: Runoob
4.2 去除首尾字符序列
- str3 = '123adc123121'
- print(str3.strip('12'))# 去除首尾字符序列 12
结果: 3abc123
5 Python startswith() 方法用于检查字符串是否是以指定子字符串开头, 如果是则返回 True, 否则返回 False. 如果参数 beg 和 end 指定值, 则在指定范围 内检查.
5. 1 以指定的字符串开头:
- tr = "this is string example....wow!!!";
- print (str.startswith( 'this' ))
- print (str.startswith( 'is', 2, 4 ))
- print (str.startswith( 'this', 2, 4 ))
结果: True,True,False
来源: http://www.bubuko.com/infodetail-3150066.html