统计字符串中元音的个数-Python
统计一段字符串中元音出现的次数,元音指['a','e','i','o','u']。使用两种方法,正则表达式和遍历字符串。
正则表达式函数为:
def byre(str):
'by re'
p=re.compile(r'[aeiou]')
print len(p.findall(str))
遍历函数为:
def bypass(str):
'by traversing'
list=['a','e','i','o','u']
print sum(1 for x in str if x in list)
写完后,想测试下二者运行时间上有没有区别,写个计算运行时间的函数time()。
def runtime(fun):
start=clock()
fun
end=clock()
print 'Run %s Time:%s' %(fun,end-start)
随机,大量字符串,统计两个函数运行时间。二者运行时间相似,正则表达式稍微占点优势。
完整的代码下载:lenstringcount.py (592 bytes)
相关阅读