View Full Version : Python: List to String

Mar 4, 2008, 11:15 PM
how can i get the list to print out like this (to a output file)

ex input: 10


def get_factor(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

m = input ("Please enter a number greater than 2: ")
outfile = 'primes-'+str(m)+'.txt'
output = open (outfile, "w")

nn = get_factor(m)
nnn = (str(nn[1:]))

#for i in range(len(nnn)):
print "Found", len(get_factor(m)), "Numbers; please check the file primes-",m,".txt"
print nn
output.write (nnn)


Mar 5, 2008, 01:33 AM
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)))
out_file.close()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.