How to ignore capitalization BUT return same capitalization as input
<p>My code intends to identify the first non-repeating string characters, empty strings, repeating strings (i.e. <code>abba</code> or <code>aa</code>), but it's also meant to treat lower and upper case input as the same character while returning the accurate non-repeating character in it's orignial case input. </p>

<pre><code>def first_non_repeat(string):
    order = []
    counts = {}
    for x in string:
        if x in counts and x.islower() == True:
            counts[x] += 1
        else:
            counts[x] = 1 
            order.append(x)
    for x in order:
        if counts[x] == 1:
            return x
    return ''
</code></pre>

<p>My logic on line 5 was that if I make all letter inputs lowercase, then it would iterate through the string input and not distinguish by case. But as of now, take the input <code>'sTreSS'</code>and output  is <code>'s'</code> when really I need <code>'T'</code>. If the last two <code>S</code>'s were lowercase, then it would be <code>'T'</code> but I need code flexible enough to handle any case input. </p>

<p>The point is that <code>x</code> in <code>counts</code> is searched for in a case-insensitive way. You have to implement your own case insensitive Dictionary, or use regular expressions to detect repeating letters:</p>

<pre><code>import re
def first_non_repeat(string):
    r = re.compile(r'([a-z])(?=.*\1)', re.I|re.S)
    m = r.search(string)
    while m:
        string = re.sub(m.group(1), '', string, re.I)
        m = r.search(string)
    return string[0]

print(first_non_repeat('sTreSS'))
</code></pre>

<p>See the <a href="http://ideone.com/l5Stt1" rel="nofollow">Python demo</a></p>

<p>The <code>([a-z])(?=.*\1)</code> regex finds any ASCII letter that also appears somewhere ahead (note that <code>([a-z])</code> <em>captures</em> the char into Group 1 and the <code>(?=.*\1)</code> is a lookahead where <code>\1</code> matches the same char captured into Group 1 after any 0+ characters matched with <code>.*</code> pattern, and <code>re.S</code> flag helps support strings with linebreaks).</p>

<p>The <code>re.sub</code> will remove all the found letters in a case insensitive way, so we will only get unique characters in the <code>string</code> after the <code>while</code> block.</p>

python string case