在python中检查字符串是否只包含一种字母类型的更简单方法

在python中检查字符串是否只包含一种字母类型的更简单方法,python,string,python-3.x,Python,String,Python 3.x,我有一个字符串'829383&&*&@使用filter和str.isalpha函数创建一个只包含字母的子列表,然后创建一个集合。最终长度必须为1,否则不符合您的条件 v="829383&&&@<<<<>><>GG" print(len(set(filter(str.isalpha,v)))==1) Jean Francois的答案实际上是我99%的时间都在使用的答案,但是对于字符串很大的情况,您可能需要一个解决方案,该解

我有一个字符串
'829383&&*&@使用
filter
str.isalpha
函数创建一个只包含字母的子列表,然后创建一个集合。最终长度必须为1,否则不符合您的条件

v="829383&&&@<<<<>><>GG"

print(len(set(filter(str.isalpha,v)))==1)

Jean Francois的答案实际上是我99%的时间都在使用的答案,但是对于字符串很大的情况,您可能需要一个解决方案,该解决方案将在检测到第二个唯一字符时立即返回,而不是完成处理:

from future_builtins import map, filter  # Only on Py2, to get lazy map/filter

from itertools import groupby, islice
from operator import itemgetter

# Remove non-alphas, then reduce consecutive identical alphabetic characters
# to a single instance of that character
lets = map(itemgetter(0), groupby(filter(str.isalpha, somestr)))

# Skip the first result, and if we find a second, then there was more than one
# in the string
if next(islice(lets, 1, None), None) is not None:
   # There were at least two unique alphabetic characters
else:
   # There were only 0-1 unique alphabetic characters
在没有islice的情况下,可以将任何字母与一个字母区分开来,如下所示:

atleastone = next(lets, None) is not None
multiple = next(lets, None) is not None

我不完全清楚你所说的“字母类型”是什么意思。为什么你关心第二个字符串中的A,而不关心第一个字符串中的数字和符号?猜测,因为A是字母,数字和符号不是。