"cannot concatenate" str "objects and" list "" keeps growing :(

I am writing a python program. The program calculates Latin squares using two numbers that the user enters on the previous page. But, but the error keeps popping up, "cannot concatenate 'str' and 'list' objects here, here is the program:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

# enable debugging
import cgi
import cgitb
cgitb.enable()

def template(file, **vars):
    return open(file, 'r').read() % vars

print "Content-type: text/html\n"
print

form = cgi.FieldStorage() # instantiate only once!
num_1 = form.getfirst('num_1')
num_2 = form.getfirst('num_2')

int1r = str(num_1)
int2r = str(num_2)

def calc_range(int2r, int1r):
    start = range(int2r, int1r + 1)
    end = range(1, int2r)
    return start+end


int1 = int(int1r)

int2 = int(int2r)

out_str = ''

for i in range(0, int1):
    first_line_num = (int2 + i) % int1
    if first_line_num == 0:
        first_line_num = int1
    line = calc_range(first_line_num, int1)
out_str += line


print template('results.html', output=out_str, title="Latin Squares")

      

+2


source to share


4 answers


range

returns a list object, so when you say

line = calc_range(first_line_num, int1)

      



You assign the list line

. This is why it out_str += line

throws an error.

You can use str()

to convert the list to a string, or you can create a string in another way to get the results you are looking for.

+4


source


By doing out_str += line

, you are trying to add a list (from calc_range) to a string. I don't even know what this is supposed to do, but where is the problem.



+1


source


You didn't say which line you're getting the error from, but I'm guessing it is:

out_str += line

      

The first variable is a string. The second is a list of numbers. You cannot concatenate a list into a string. I don't know what you are trying to do exactly, but what about:

out_str += ", ".join(line)

      

This will add comma-linked numbers to out_str.

+1


source


calc_range()

returns a list; however you are trying to add it to string ( out_str

).

It looks like your code is incomplete - don't you want to do something with the range of numbers returned calc_range()

? How, say, something with the form?

line = ''.join(num_1[index] for index in calc_range(first_line_num, int1))

      

I don't know what you want - but could there be something like this?

0


source







All Articles