Easier way to check if a string contains only one type of letter in python
<p>I have a string <code>'829383&amp;&amp;*&amp;@&lt;&lt;&lt;&lt;&gt;&gt;&lt;&gt;GG'</code>. I want a way to measure if a string has only one type of letter. For example the string above would return True, because it only has two Gs, but this string, <code>'829383&amp;&amp;*&amp;@&lt;&lt;&lt;&lt;&gt;&gt;&lt;&gt;GGAa'</code> would not. I've been iteratively going through the string having made it into an array. I was hoping someone knew an easier way. </p>

<p>Jean-Francois's answer is what I'd actually use 99% of the time, but for cases where the string is <em>huge</em> you might want a solution that will return as soon as the second unique character is detected, instead of finishing processing:</p>

<pre><code>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
</code></pre>

<p>Distinguishing no alphabetic from one alphabetic could instead be done without <code>islice</code> as:</p>

<pre><code>atleastone = next(lets, None) is not None
multiple = next(lets, None) is not None
</code></pre>

python string python-3.x