string concatenation

Eric Brunel eric_brunel at
Fri Jul 2 17:28:05 CEST 2004

Ajay wrote:
> hi!
> i am going through a for loop and want to add the strings together
> i am doing this currently
> for name in contextForm.keys():
>     context += "Input: " + name + " value: " + contextForm[name].value +
> "<BR>"
> context is meant to hold all the form values in the paper.
> however the code above doesn't work

Waht do you mean by "doesn't work"? Does it crash? Does it give an unexpected 
result? If it crashes, giving us the actual error message will help a lot.

I can see at least two reasons why it may crash:

1 - the most likely: context is not initialized. E.g:

 >>> s += 'foo'
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
NameError: name 's' is not defined

You must initialize context to the empty string before trying to append anything 
to it.

2 - less likely, but worth a mention: you should prefer:

context += "Input: %s value: %s<BR>" % (name, contextForm[name].value)

to what you've written. The reason is simple: %s will translate everything into 
a string; + will not. E.g:

 >>> "bar" + 12
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
TypeError: cannot add type "int" to string

> being new to Python, i dont know whether you can do +=

Yes, you can, except if you have a very old Python version (e.g. 1.5), where += 
will raise a SyntaxError. If this is the case, either install a newer Python 
version or use:

context = context + ...

or one of the solutions other posters already gave.

- Eric Brunel <eric (underscore) brunel (at) despammed (dot) com> -
PragmaDev : Real Time Software Development Tools -

More information about the Python-list mailing list