Add a character on a list if a situation presents
<p>I have this script:</p>

<pre><code>accounts = open("accounts.txt").readlines()

y = [x.strip().split(":") for x in accounts]

for position, account in enumerate(y):
    try:
        print ("Trying with: %s:%s @%d" % (account[0], account[1], position))
    except:
        pass
</code></pre>

<p>it opens a file (accounts.txt) that is structured like this:</p>

<pre><code>email1@email.com:test1
email2@email.com:test2
email3@email.comtest3
email4@email.comtest4
</code></pre>

<p>Since I want to split the email and the password, I'd like, if the try doesn't work (so the ":" is not in the line of the file (and account[1] doesn't exist)), to add the ":" after the ".com" of each email on the file. Is that possible? </p>

<p>The output of the third and fourth accounts should be:</p>

<pre><code>email3@email.com:test3
email4@email.com:test4
</code></pre>

<p>You can use regex for splitting your lines:</p>

<pre><code>In [37]: s1 = 'email2@email.com:test2'
In [38]: s2 = 'email3@email.comtest3'

In [42]: regex = re.compile(r'(.+\.com):?(.*)')

In [43]: regex.search(s1).groups()
Out[43]: ('email2@email.com', 'test2')

In [44]: regex.search(s2).groups()
Out[44]: ('email3@email.com', 'test3')
</code></pre>

<p>And in your code:</p>

<pre><code>regex = re.compile(r'(.+\.com):?(.*)')

with open("accounts.txt") as f:
    for ind, line in enumerate(f):
        try:
            part1, part2 = regex.search(line.strip()).groups()
        except:
            pass
        else:
            print ("Trying with: {}:{} @{}".format(part1, part2, ind))
</code></pre>

python list python-3.x for-loop split