string concatenation

A

Ajay

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

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

can you?

cheers
 
S

selwyn

you can += strings, but you need to create the variable first:

i.e.
for name in contextForm.keys():
context = ''
context += "Input: " + name + " value: " + contextForm[name].value
+ "<BR>"

concatenating a string like this is supposed to be substantially slower
than using ''.join(sequence), where you can replace the blank string
with the separator of your choice.

using your example:

for name in contextForm.keys():
sequence = ["Input: ",name, " value: ", contextForm[name].value,
"<BR>"]
context = ' '.join(sequence)

HTH
 
P

Peter Otten

selwyn said:
you can += strings, but you need to create the variable first:

i.e.
for name in contextForm.keys():
context = ''
context += "Input: " + name + " value: " + contextForm[name].value
+ "<BR>"

I guess the OP wants to collect data over the loop, i. e

context = ""
for name in contextForm.keys():
context += "Input: " + name + " value: " + contextForm[name].value
concatenating a string like this is supposed to be substantially slower
than using ''.join(sequence), where you can replace the blank string
with the separator of your choice.

using your example:

for name in contextForm.keys():
sequence = ["Input: ",name, " value: ", contextForm[name].value,
"<BR>"]
context = ' '.join(sequence)

The faster idiom will then become

sequence = []
for name in contextForm.keys():
sequence += ["Input: ", name, " value: ", contextForm[name].value,
"<BR>"]
context = "".join(sequence)

Peter
 
R

Reinhold Birkenfeld

Peter said:
The faster idiom will then become

sequence = []
for name in contextForm.keys():
sequence += ["Input: ", name, " value: ", contextForm[name].value,
"<BR>"]
context = "".join(sequence)

Where I would prefer the variant

str.join("", sequence)

as it is more readable for beginners (and demonstrates the concept of
invoking member methods as well ;)

Reinhold
 
P

Peter Otten

Reinhold said:
Where I would prefer the variant

str.join("", sequence)

as it is more readable for beginners (and demonstrates the concept of
invoking member methods as well ;)

If it prevents newbies from doing

import string
string.join("", sequence)

so be it. Real men use "".join(seq) :)

Peter

PS: And women, too.
 
R

Reinhold Birkenfeld

Peter said:
If it prevents newbies from doing

import string
string.join("", sequence)

so be it. Real men use "".join(seq) :)

Maybe I'm not a real man, but the solution I like most (for code that
extensively concatenates strings in this way) is

join = lambda x: "".join(x)

Reinhold
 
P

Peter Otten

Reinhold said:
Maybe I'm not a real man, but the solution I like most (for code that

Of course not, because real men never show doubt :)
(If hard pressed, I'll admit I'm no more "real" than you in that respect)
extensively concatenates strings in this way) is

join = lambda x: "".join(x)

Vicious lambda - tricks you into believing that you need it.
join = " ".join
join(["all", "of", "us"]) 'all of us'

Now that's an idiom we both like, I suppose.

Peter
 
S

Scott David Daniels

Ajay said:
...
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.
Although the 'collect in a list, join at leisure' plan often is best,
don't forget StringIO. This situation is tailor-made for StringIO.

from cStringIO import StringIO

dest = StringIO()
for name in contextForm.keys():
print >>dest, 'Input:', name, 'value:', contextForm[name].value,
print >>dest, '<BR>'
whatever = dest.getvalue()
 
E

Eric Brunel

Ajay said:
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:
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:
Traceback (most recent call last):
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.

HTH
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,734
Messages
2,569,441
Members
44,832
Latest member
GlennSmall

Latest Threads

Top