更简单的方法来检查字符串是否只包含python

时间:2016-10-19 21:06:36

标签: python string python-3.x

我有一个字符串'829383&&*&@<<<<>><>GG'。我想要一种方法来衡量字符串是否只有一种字母。例如,上面的字符串将返回True,因为它只有两个G,但是这个字符串'829383&&*&@<<<<>><>GGAa'不会。我已经迭代地通过字符串使其成为一个数组。我希望有人知道一种更简单的方法。

2 个答案:

答案 0 :(得分:2)

使用filterstr.isalpha函数创建仅包含字母的子列表,然后创建一个集合。最终长度必须为1或您的条件不符合。

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

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

答案 1 :(得分:1)

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

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