Return true if all characters in the string are alphabetic and there is at least one character, false otherwise. Alphabetic characters are those characters defined in the Unicode character database as “Letter”
my_list = [item for item in my_list if item.isalpha()]
import re
my_list = [ 'hello' , 'hi', '4tim', '342' 'adn322' ]
def isalpha(mylist):
return [item for item in mylist if item.isalpha()]
def fisalpha(mylist):
return filter(str.isalpha,mylist)
def regex(mylist,myregex = re.compile(r'\d')):
return [s for s in mylist if not myregex.search(s)]
def isdigit(mylist):
return [x for x in mylist if not any(c.isdigit() for c in x)]
import timeit
for func in ('isalpha','fisalpha','regex','isdigit'):
print func,timeit.timeit(func+'(my_list)','from __main__ import my_list,'+func)
我发现使用^{} 最优雅,但它也会删除包含其他非字母字符的项:
我会用正则表达式:
就时间而言,在示例数据上使用regex要比isdigit解决方案快得多。诚然,它比
isalpha
慢,但其行为与标点符号、空白等稍有不同。由于问题没有指定这些字符串应该发生什么,所以不清楚哪个是最好的解决方案。以下是我的结果:
不带regex:
相关问题 更多 >
编程相关推荐