Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符
Python split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串
下面举例来实现一下
text = " 镇海 雅乐 学校 二年级 的 小朋友 到 一条 小路 的 一边 植树 . 小朋友 们 每隔 2 米 种 一棵树 ( 马路 两头 都 种 了 树 ) , 最后 发现 一共 种 了 11 棵 , 这 条 小路 长 多少 米 . "
print(text)
print("="*60)
print(text.strip())
print("="*60)
print(text.split())
print("="*60)
print(text.strip().split())
实验分析:
通过实验我们可以看见原字符串中头尾的空格已经被删除了。并且也已经按照空格进行了分词。
Python count() 方法用于统计字符串里某个字符或子字符串出现的次数。可选参数为在字符串搜索的开始与结束位置
str = "this is string example....wow!!!";
sub = "i";
print "str.count(sub, 4, 40) : ", str.count(sub, 4, 40)
sub = "wow";
print "str.count(sub) : ", str.count(sub)
'''
输出结果为
str.count(sub, 4, 40) : 2
str.count(sub) : 1
'''