- 论坛徽章:
- 0
|
默认的快不快其实取决于有没有加载psyco。。。。。。。。。。
- #coding:utf-8
- str_strip=lambda s:s.strip()
- def str_strip2(s):
- left_index,right_index=0,len(s)-1
- left_char,right_char=s[left_index],s[right_index]
- while left_char.isspace():
- left_index+=1
- left_char=s[left_index]
- while right_char.isspace():
- right_index-=1
- right_char=s[right_index]
- return s[left_index:right_index+1]
- def str_strip3(str):
- start = 0
- end = len(str)
- for c in str:
- if c.isspace():
- start += 1
- else:
- break
- for c in str[::-1]:
- if c.isspace():
- end -= 1
- else:
- break
- return str[start:end]
- import re
- regex_strip=lambda s:re.sub(r'^\s*|\s*$', '', s)
- regex_strip2=lambda s:re.sub("^\s*(.+?)\s*$",lambda x:x.group(1),s)
- if __name__=="__main__":
- from timeit import Timer
- import sys
- if sys.argv[-1]=='psyco':
- try:
- import psyco
- psyco.full()
- except ImportError,e:
- sys.exit(e)
- print Timer("str_strip(' sjaksja ')","from __main__ import str_strip").timeit(10000)
-
- print Timer("str_strip2(' sjaksja ')","from __main__ import str_strip2").timeit(10000)
- print Timer("str_strip3(' sjaksja ')","from __main__ import str_strip3").timeit(10000)
- print Timer("regex_strip(' sjaksja ')","from __main__ import regex_strip").timeit(10000)
-
- print Timer("regex_strip2(' sjaksja ')","from __main__ import regex_strip2").timeit(10000)
复制代码 |
|