How do I print each element of a list on individual lines, preceded by the line number in python?

StackOverflow https://stackoverflow.com/questions/13403875

سؤال

How can I print each individual element of a list on separate lines, with the line number of the element printed before the element? The list information will also be retrieved from a text file.

So far I have,

import sys
with open(sys.argv[1], 'rt') as num:
    t = num.readlines()
    print("\n"[:-1].join(t))

Which currently gives the read-out:

Blah, blah, blah
etc, etc, etc
x, x, x

But I want this read-out:

1. Blah, blah, blah
2. etc, etc, etc
3. x, x, x

Thanks for you help.

هل كانت مفيدة؟

المحلول

you can use enumerate() and use str.rstrip() to remove the all types of trailing whitespaces from the string. and you can also use rstrip('\n') if you're sure that the newline is going to be \n only.:

for i,x in enumerate(t,1):
    print ("{0}. {1}".format(i,x.rstrip()))

نصائح أخرى

This seems easiest with enumerate, printing each line as you go:

import sys
with open(sys.argv[1], 'r') as num:
    for i,line in enumerate(num,1):
        print("%d. %s"%(i,line[:-1]))  #equivalent to `"{0}. {1}".format(i,line[:-1])`

Of course, you could wrap the whole thing in a generator if you want to use join:

def number_lines(fname):
    with open(fname,'r') as f:
       for i,line in enumerate(f,1):
           yield "%d. %s"%(i,line[:-1])

print('\n'.join(number_lines(sys.argv[1])))

Using fileinput.input it is possible to iterate over file line by line. When fileinput.input returns next line, we enumerate it to track line number. As input already contains newline we use end="" in print method so it doesn't append unnecessary newline. Using format to convert line number and content to formated representation.

import fileinput

for number, line in enumerate(fileinput.input(['some_file.txt']), 1):
    print('{0}. {1}'.format(number, line), end="")
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top