Add letters to string conditionally
<p><strong>Input</strong>: <code>1 10 avenue</code></p>

<p><strong>Desired Output</strong>: <code>1 10th avenue</code></p>

<p>As you can see above I have given an example of an input, as well as the desired output that I would like. Essentially I need to look for instances where there is a number followed by a certain pattern (avenue, street, etc). I have a list which contains all of the patterns and it's called <code>patterns</code>.</p>

<p>If that number does not have "th" after it, I would like to add "th". Simply adding "th" is fine, because other portions of my code will correct it to either "st", "nd", "rd" if necessary.</p>

<p><strong>Examples:</strong></p>

<p><code>1 10th avenue</code> OK</p>

<p><code>1 10 avenue</code> NOT OK, TH SHOULD BE ADDED!</p>

<p>I have implemented a working solution, which is this:</p>

<pre><code>def Add_Th(address):
    try:
        address = address.split(' ')
    except AttributeError:
        pass
    for pattern in patterns:
        try:
            location = address.index(pattern) - 1
            number_location = address[location]
        except (ValueError, IndexError):
            continue
        if 'th' not in number_location:
            new = number_location + 'th'
            address[location] = new
        address = ' '.join(address)

    return address
</code></pre>

<p>I would like to convert this implementation to <strong>regex</strong>, as this solution seems a bit messy to me, and occasionally causes some issues. I am not the best with regex, so if anyone could steer me in the right direction that would be greatly appreciated!</p>

<p>Here is my current attempt at the regex implementation:</p>

<pre><code>def add_th(address):

    find_num = re.compile(r'(?P&lt;number&gt;[\d]{1,2}(' + "|".join(patterns + ')(?P&lt;following&gt;.*)')
    check_th = find_num.search(address)

    if check_th is not None:
        if re.match(r'(th)', check_th.group('following')):
            return address
        else:
            # this is where I would add th. I know I should use re.sub, i'm just not too sure
            # how I would do it
    else:
        return address
</code></pre>

<p>I do not have a lot of experience with regex, so please let me know if any of the work I've done is incorrect, as well as what would be the best way to add "th" to the appropriate spot.</p>

<p>Thanks.</p>

<p>Just one way, finding the positions <strong>behind a digit</strong> and <strong>ahead of one of those pattern words</strong> and placing <code>'th'</code> into them:</p>

<pre><code>&gt;&gt;&gt; address = '1 10 avenue 3 33 street'
&gt;&gt;&gt; patterns = ['avenue', 'street']
&gt;&gt;&gt; 
&gt;&gt;&gt; import re
&gt;&gt;&gt; pattern = re.compile(r'(?&lt;=\d)(?= ({}))'.format('|'.join(patterns)))
&gt;&gt;&gt; pattern.sub('th', address)
'1 10th avenue 3 33th street'
</code></pre>

python regex