Thavivelball Thavivelball - 1 year ago 76
Python Question

Print the current number of item in a cycle for x in y

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:

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

Trying with: @1
Trying with: @2
Trying with: @3

Answer Source

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))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download