Python: List to String

Discussion in 'Mac Programming' started by iHerzeleid, Mar 4, 2008.

  1. macrumors 6502a


    May 5, 2007
    how can i get the list to print out like this (to a output file)

    ex input: 10


  2. macrumors 601


    Jan 6, 2004
    Western US
    Code: PIMPED!

    def get_factors(x):
    	l = []
    	for i in range(1, (x + 2) / 2):
    		if (x % i == 0 and i != 1 and i != x):
    			l = l + [i]
    	return l
    max_num = input("Please enter a number greater than 2: ")
    out_file_name = "factors-" + str(max_num) + ".txt"
    out_file = open(out_file_name, "w")
    factors = get_factors(max_num)
    print "Found " + str(len(factors)) + " numbers; please check the file " + out_file_name + "."
    print factors
    out_file.write("\n".join(map(str, factors)))
    Basically I'm using the string.join operator to join the list, but since join doesn't work with integers, I use the map function to turn each element of the list into a string first. Not sure if this is the most efficient method of going about it, but it works. Also notice I cleaned a few things up. In particular, you should really avoid calculating values and running functions more than once, as you were doing building the file name and then with the get_factors function, which could potentially be expensive.

Share This Page