博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【Python】从字符串中提取字母字符串的几种方法
阅读量:4170 次
发布时间:2019-05-26

本文共 1290 字,大约阅读时间需要 4 分钟。

最近作为技术面试官协助公司招聘新人,应聘者大多都学习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的英文帮助文档。

转载地址:http://rmkai.baihongyu.com/

你可能感兴趣的文章
jpa 和 hibernate 的联系
查看>>
SpringBoot之@SpringBootApplication注解
查看>>
ajax 传JSON 写法
查看>>
SpringBoot之web发展史
查看>>
SpringBoot之开发web页面
查看>>
SpringBoot之快速部署
查看>>
springBoot之jar包在后台(运行:编写start、stop脚本)
查看>>
redis学习
查看>>
SpringBoot之application.properties文件能配置的属性
查看>>
javaWeb监听器、过滤器、拦截器
查看>>
RESTFUL风格的接口
查看>>
后台参数验证配置
查看>>
SpringBoot之外置Tomcat配置
查看>>
java 删除 list 中的元素
查看>>
idea启动优化
查看>>
java发展史
查看>>
Java内存区域
查看>>
数据库与模式的区别
查看>>
数字签名的原理
查看>>
showDialog
查看>>