如果您使用的是 ascii,则可以使用 str.translate 从小写字符串中删除所有无数字和字母的内容
>>> from string import ascii_letters, digits
>>> ascii = set(chr(e) for e in range(128))
>>> ascii_sans_alpha = ''.join(ascii.difference(ascii_letters + digits))
>>> a = " Kingston-(USB) = 1GB, 2GB, 32GB . . . "
>>> a.lower().translate(None,ascii_sans_alpha)
'kingstonusb1gb2gb32gb'
这有多快?使用 timeit 参考
>>> def mgilson(a, good = set(string.ascii_lowercase + string.digits)):
return ''.join(x for x in a.lower() if x in good)
>>> def blender_re(a):
return re.sub(r'[^a-z0-9]', '', a.lower())
>>> def blender_gen(a, allowed = string.lowercase + string.digits):
return ''.join(c for c in a.lower() if c in allowed)
>>> def blender_fast(a, allowed = set(string.lowercase + string.digits)):
return ''.join(filter(allowed.__contains__, a.lower()))
>>> def abhijit(a, ascii_sans_alpha = ''.join(set(chr(e) for e in range(128)).difference(ascii_letters + digits))):
return a.lower().translate(None,ascii_sans_alpha)
>>> time_dict = {"abhijit": "from __main__ import string, a",
"blender_re":"from __main__ import re, a, abhijit",
"blender_gen": "from __main__ import string, a",
"blender_fast": "from __main__ import string, a",
"mgilson": "from __main__ import string, a"}
>>> for k, v in time_dict.items():
t = timeit.Timer(stmt="{}(a)".format(k),setup = "{},{}".format(v,k))
print "Timing for {} is {}".format(k, t.timeit(100000))
Timing for blender_fast is 0.573348026237
Timing for blender_re is 0.632169556846
Timing for blender_gen is 0.720916486331
Timing for mgilson is 0.586592185393
Timing for abhijit is 0.203489867547
>>>