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

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

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

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

import re
from functools import wraps


def 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_timer
def get_alpha_str1(s):
    result = ''.join([x for x in s if x.isalpha()])
    return result


@fn_timer
def get_alpha_str2(s):
    result = ''.join(re.findall(r'[A-Za-z]', s))
    return result


@fn_timer
def get_alpha_str3(s):
    result = re.sub(r'[^A-Za-z]', '', s)
    return result


@fn_timer
def get_alpha_str4(s):
    result = ''.join(re.split(r'[^A-Za-z]', s))
    return result


if __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的英文帮助文档。

  • 12
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值