【Python】从字符串中提取字母字符串的几种方法

来源:互联网 发布:mac book pro 2015 编辑:程序博客网 时间:2024/06/05 18:28

最近作为技术面试官协助公司招聘新人,应聘者大多都学习python 1~2年,不过在面试过程中,我问了很简单的题目,好多都没有完全的回答上了。 不说了,直接贴题目:

题目: s = 'abc@124, efg opAs4',请把其中的字母字符串拿出来,组合成新字符串。 

我就自己想到的方法列举如下,并且就各自性能对比如下:

import refrom functools import wrapsdef fn_timer(function):    @wraps(function)    def function_timer(*args, **kwargs):        import time        t0 = time.time()        result = function(*args, **kwargs)        t1 = time.time()        print('%s costs %s (s)' %(function.func_name, t1 - t0))        return result    return function_timer@fn_timerdef get_alpha_str1(s):    result = ''.join([x for x in s if x.isalpha()])    return result@fn_timerdef get_alpha_str2(s):    result = ''.join(re.findall(r'[A-Za-z]', s))    return result@fn_timerdef get_alpha_str3(s):    result = re.sub(r'[^A-Za-z]', '', s)    return result@fn_timerdef get_alpha_str4(s):    result = ''.join(re.split(r'[^A-Za-z]', s))    return resultif __name__ == '__main__':    with open('text.txt', 'r') as f:        s = f.read()    print(len(s))    get_alpha_str1(s)    get_alpha_str2(s)    get_alpha_str3(s)    get_alpha_str4(s)

执行结果:

5623680
get_alpha_str1 costs 0.569999933243 (s)
get_alpha_str2 costs 0.642999887466 (s)
get_alpha_str3 costs 0.442999839783 (s)
get_alpha_str4 costs 0.384999990463 (s)


由此可见第四种效率最高;

说明text.txt文本大概5.5M,主要来自于python3.6.2的英文帮助文档。

原创粉丝点击