string concatenation

Discussion in 'Python' started by Ajay, Jun 28, 2004.

  1. Ajay

    Ajay Guest

    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
    --
    Ajay Brar,
    CS Honours 2004
    Smart Internet Technology Research Group





    ----------------------------------------------------------------
    This message was sent using IMP, the Internet Messaging Program.
     
    Ajay, Jun 28, 2004
    #1
    1. Advertising

  2. Ajay

    selwyn Guest

    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






    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
    >
    > being new to Python, i dont know whether you can do +=
    >
    > can you?
    >
    > cheers
    > --
    > Ajay Brar,
    > CS Honours 2004
    > Smart Internet Technology Research Group
    >
    >
    >
    >
    >
    > ----------------------------------------------------------------
    > This message was sent using IMP, the Internet Messaging Program.
    >
     
    selwyn, Jun 28, 2004
    #2
    1. Advertising

  3. Ajay

    Peter Otten Guest

    selwyn wrote:

    > 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
     
    Peter Otten, Jun 28, 2004
    #3
  4. Peter Otten wrote:

    > 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


    --
    Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows
    mitbrächte, wäre das bedauerlich. Was bei Windows der Umfang eines
    "kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk.
    -- David Kastrup in de.comp.os.unix.linux.misc
     
    Reinhold Birkenfeld, Jun 28, 2004
    #4
  5. Ajay

    Peter Otten Guest

    Reinhold Birkenfeld wrote:

    > 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.
     
    Peter Otten, Jun 28, 2004
    #5
  6. Peter Otten wrote:
    > Reinhold Birkenfeld wrote:
    >
    >> 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) :)


    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

    --
    Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows
    mitbrächte, wäre das bedauerlich. Was bei Windows der Umfang eines
    "kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk.
    -- David Kastrup in de.comp.os.unix.linux.misc
     
    Reinhold Birkenfeld, Jun 28, 2004
    #6
  7. Ajay

    Peter Otten Guest

    Reinhold Birkenfeld wrote:

    > 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
     
    Peter Otten, Jun 28, 2004
    #7
  8. Peter Otten wrote:
    > Reinhold Birkenfeld wrote:
    >
    >> 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.


    Yes, you're right. How could I...

    >>>> join = " ".join
    >>>> join(["all", "of", "us"])

    > 'all of us'
    >>>>

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


    Affirmative.

    Reinhold

    --
    Wenn eine Linuxdistribution so wenig brauchbare Software wie Windows
    mitbrächte, wäre das bedauerlich. Was bei Windows der Umfang eines
    "kompletten Betriebssystems" ist, nennt man bei Linux eine Rescuedisk.
    -- David Kastrup in de.comp.os.unix.linux.misc
     
    Reinhold Birkenfeld, Jun 28, 2004
    #8
  9. Ajay wrote:
    >...
    > 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()

    --
    -Scott David Daniels
     
    Scott David Daniels, Jul 2, 2004
    #9
  10. Ajay

    Eric Brunel Guest

    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.

    HTH
    --
    - Eric Brunel <eric (underscore) brunel (at) despammed (dot) com> -
    PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com
     
    Eric Brunel, Jul 2, 2004
    #10
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. walala
    Replies:
    3
    Views:
    4,885
    walala
    Sep 18, 2003
  2. Sukhbir Dhillon
    Replies:
    1
    Views:
    6,302
    Joe Smith
    Apr 5, 2004
  3. Daniel Bergquist

    String Concatenation problems

    Daniel Bergquist, Jul 13, 2004, in forum: Perl
    Replies:
    2
    Views:
    509
    Joe Smith
    Jul 16, 2004
  4. Sparky Arbuckle

    String Concatenation & Removing Space

    Sparky Arbuckle, Sep 1, 2005, in forum: ASP .Net
    Replies:
    5
    Views:
    633
    Sparky Arbuckle
    Sep 1, 2005
  5. Andrew Berg
    Replies:
    13
    Views:
    1,365
    Andrew Berg
    Jul 11, 2011
Loading...

Share This Page