Search code examples
pythonfor-looparcpy

Print out the items which went through For loop? python 2.7


I am new in python. I have a for loop inside which I have if ...: condition.

I want to print out the (list) of items which went through the for loop.

Ideally, items should be separated by spaces or by commas. This is a simple example, intended to use with arcpy to print out the processed shapefiles.

Dummy example:

for x in range(0,5):
    if x < 3:
        print "We're on time " + str(x)

What I tried without success inside and outside of if and for loop:

print "Executed " + str(x)

Expected to get back (but not in list format), maybe through something like arcpy.GetMessages() ?

Executed 0 1 2 

Solution

  • phrase = "We're on time "
    
    # create a list of character digits (look into list comprehensions and generators)
    nums = [str(x) for x in range(0, 5) if x < 3]
    
    # " ".join() creates a string with the elements of a given list of strings with space in between
    # the + concatenates the two strings
    print(phrase + " ".join(nums))
    

    Note. A reason for the downvotes could help us new users understand how things should be.