-1

I have this script:

accounts = open("accounts.txt").readlines()

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

for account in y:
    print ("Trying with: %s:%s" % (account[0], account[1]))

the file accounts.txt is structred like this:

email1@email.com:test1
email2@email.com:test2
email3@gmail.com:test3

How can i add to the print "Trying with... bla bla" the current line of the account? An output like:

Trying with: email1@email.com:test1 @1
Trying with: email2@email.com:test1 @2
Trying with: email3@email.com:test1 @3
CatchJoul
  • 87
  • 2
  • 8
  • 1
    Possible duplicate of [Accessing the index in Python 'for' loops](http://stackoverflow.com/questions/522563/accessing-the-index-in-python-for-loops) – Łukasz Rogalski Sep 18 '16 at 17:14

2 Answers2

1

You can use enumerate(), with the start argument as suggested by @JonClements:

for i, account in enumerate(y, start=1):
    print ("Trying with: %s:%s @%d" % (account[0], account[1], i))

You can also use unpacking to make the line more readable:

for i, (mail, name) in enumerate(y, start=1):
    print ("Trying with: %s:%s @%d" % (mail, name, i))

Finally, as @idjaw notified it, there is a better way to format string which is recommended over the old style:

for i, (mail, name) in enumerate(y, start=1):
    print("Trying with: {}:{} @{}".format(mail, name, i))
Delgan
  • 18,571
  • 11
  • 90
  • 141
  • However, I would directly use string formatting here and just do: `"Trying with: {}:{} @{}".format(account[0], account[1], i)` – idjaw Sep 18 '16 at 17:13
  • You can skip the `i + 1` as `enumerate` takes a start argument: `enumerate(y, start=1)` is somewhat more explicit to what you're using `i` for. – Jon Clements Sep 18 '16 at 17:18
  • Also - new style string formatting wasn't introduced in Python 3 - it's been around since Python 2.6 – Jon Clements Sep 18 '16 at 17:19
0

You're looking for enumerate:

for position, account in enumerate(y):
    print ("Trying with: %s:%s @%d" % (account[0], account[1], position))
ForceBru
  • 43,482
  • 10
  • 63
  • 98