String concatenation

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Leif B. Kristensen

    String concatenation

    Having recently started with Python, I've written this little function
    to retrieve place parts from a database and concatenate them to a
    string. While it certainly works, and is also considerably shorter than
    the PHP code that I originally wrote, I'm pretty convinced that there
    should be an even better way to do it. Can anybody show me how to write
    the string concatenation part in a more Pythonesque syntax?

    def get_place(x):
    c=db.cursor()
    c.execute("sele ct place_lvl1, place_lvl2, \
    place_lvl3, place_lvl4, place_lvl5 \
    from place where place_id = %d" % (x))
    res=c.fetchone( )
    place = ''
    for i in range(5):
    tmp = res[i]
    if tmp[:1] != '-' and len(tmp) != 0:
    place = place + ', ' + (res[i])
    return place[2:]

    regards,
    --
    Leif Biberg Kristensen

    Validare necesse est
  • Paul Rubin

    #2
    Re: String concatenation

    "Leif B. Kristensen" <junkmail@solum slekt.org> writes:[color=blue]
    > Having recently started with Python, I've written this little function
    > to retrieve place parts from a database and concatenate them to a
    > string. While it certainly works, and is also considerably shorter than
    > the PHP code that I originally wrote, I'm pretty convinced that there
    > should be an even better way to do it. Can anybody show me how to write
    > the string concatenation part in a more Pythonesque syntax?
    > ...
    > for i in range(5):
    > tmp = res[i]
    > if tmp[:1] != '-' and len(tmp) != 0:
    > place = place + ', ' + (res[i])
    > return place[2:][/color]

    Not tested:

    tmp = [x for x in res if x and x[0] != '-']
    return ', '.join(tmp)

    Explanation:

    1) you can use "for x in res" instead of looping through range(5),
    since you know that res has 5 elements (from the sql result).

    2) x[:1] is the same as x[0] as long as x has at least 1 char (otherwise
    it throws an exception)

    3) To prevent the exception, test for x being nonempty BEFORE examining x[0]

    4) sep.join(string list) is the standard way to join a bunch of strings
    together, separated by sep.

    Comment

    • Leif B. Kristensen

      #3
      Re: String concatenation

      Paul Rubin wrote:
      [color=blue]
      > Not tested:
      >
      > tmp = [x for x in res if x and x[0] != '-']
      > return ', '.join(tmp)[/color]

      Paul,
      that looks a lot more like the examples in "Dive Into Python" which I'm
      reading at the moment. But the snake won't swallow:

      tmp = [x for x in res if x and x[0] != '-']
      ^
      SyntaxError: invalid syntax

      I wonder what it's really trying to tell me?

      regards,
      --
      Leif Biberg Kristensen

      Validare necesse est

      Comment

      • Erik Max Francis

        #4
        Re: String concatenation

        "Leif B. Kristensen" wrote:
        [color=blue]
        > that looks a lot more like the examples in "Dive Into Python" which
        > I'm
        > reading at the moment. But the snake won't swallow:
        >
        > tmp = [x for x in res if x and x[0] != '-']
        > ^
        > SyntaxError: invalid syntax
        >
        > I wonder what it's really trying to tell me?[/color]

        Probably you included the initial spaces, which is a no-no:
        [color=blue][color=green][color=darkred]
        >>> a = 1
        >>> b = 2[/color][/color][/color]
        File "<stdin>", line 1
        b = 2
        ^
        SyntaxError: invalid syntax

        --
        __ Erik Max Francis && max@alcyone.com && http://www.alcyone.com/max/
        / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
        \__/ They love too much that die for love.
        -- (an English proverb)

        Comment

        • Leif B. Kristensen

          #5
          Re: String concatenation

          Erik Max Francis wrote:
          [color=blue]
          > Probably you included the initial spaces, which is a no-no:[/color]

          No I didn't. The text is properly aligned. The relevant code now looks
          exactly like this:

          res=c.fetchone( )
          tmp=[x for x in res if x and x[0] != '-']
          return ', '.join(tmp)

          And here's what the interpreter says:

          tmp=[x for x in res if x and x[0] != '-']
          ^
          SyntaxError: invalid syntax

          The marker has moved to the right, maybe because I removed the spaces on
          both sides of the = sign?

          regards,
          --
          Leif Biberg Kristensen

          Validare necesse est

          Comment

          • Erik Max Francis

            #6
            Re: String concatenation

            "Leif B. Kristensen" wrote:
            [color=blue]
            > And here's what the interpreter says:
            >
            > tmp=[x for x in res if x and x[0] != '-']
            > ^
            > SyntaxError: invalid syntax
            >
            > The marker has moved to the right, maybe because I removed the spaces
            > on
            > both sides of the = sign?[/color]

            At this point I don't know what's going on since there's a communication
            problem; Python's exception specification is based on the code you
            entered, not the code it thought you meant, so you're having a
            cutting-and-pasting problem at least on one side here.

            If indentation is not to blame, it's possible that the problem is that
            you're not running a version of Python that understands list
            comprehensions.

            --
            __ Erik Max Francis && max@alcyone.com && http://www.alcyone.com/max/
            / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
            \__/ They love too much that die for love.
            -- (an English proverb)

            Comment

            • Leif B. Kristensen

              #7
              Re: String concatenation

              Erik Max Francis wrote:
              [color=blue]
              > At this point I don't know what's going on since there's a
              > communication problem; Python's exception specification is based on
              > the code you entered, not the code it thought you meant, so you're
              > having a cutting-and-pasting problem at least on one side here.[/color]

              Erik,
              After entering Paul's two lines by hand, it suddenly works. You must be
              right about the cutting-and-pasting problem, though I don't understand
              why lifting text from KNode to KWrite shouldn't work.
              [color=blue]
              > If indentation is not to blame, it's possible that the problem is that
              > you're not running a version of Python that understands list
              > comprehensions.[/color]

              bash-2.05b$ python
              Python 2.3.3 (#1, Jan 24 2004, 10:16:14)
              [GCC 3.2.3 20030422 (Gentoo Linux 1.4 3.2.3-r3, propolice)] on linux2
              Type "help", "copyright" , "credits" or "license" for more information.

              regards,
              --
              Leif Biberg Kristensen

              Validare necesse est

              Comment

              • Erik Max Francis

                #8
                Re: String concatenation

                "Leif B. Kristensen" wrote:
                [color=blue]
                > After entering Paul's two lines by hand, it suddenly works. You must
                > be
                > right about the cutting-and-pasting problem, though I don't understand
                > why lifting text from KNode to KWrite shouldn't work.[/color]

                Maybe it's grabbing tabs, or obscure unprintable whitespace you can't
                see. Certainly what you're pasting in to these posts is intended,
                whether or not you did that manually.

                --
                __ Erik Max Francis && max@alcyone.com && http://www.alcyone.com/max/
                / \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
                \__/ It's soulful music. It doesn't necessarily sound like ... soul ...
                -- Sade Adu

                Comment

                • Leif B. Kristensen

                  #9
                  Re: String concatenation

                  Paul Rubin wrote:
                  [color=blue]
                  > "Leif B. Kristensen" <junkmail@solum slekt.org> writes:[color=green]
                  >> for i in range(5):
                  >> tmp = res[i]
                  >> if tmp[:1] != '-' and len(tmp) != 0:
                  >> place = place + ', ' + (res[i])
                  >> return place[2:][/color]
                  >
                  > tmp = [x for x in res if x and x[0] != '-']
                  > return ', '.join(tmp)[/color]

                  Now I got it working, and it's really neat! It's almost incredible that
                  you can do all this with just two lines of code.

                  Thank you very much.

                  regards,
                  --
                  Leif Biberg Kristensen

                  Validare necesse est

                  Comment

                  • Leif B. Kristensen

                    #10
                    Re: String concatenation

                    Erik Max Francis wrote:
                    [color=blue]
                    > Maybe it's grabbing tabs, or obscure unprintable whitespace you can't
                    > see. Certainly what you're pasting in to these posts is intended,
                    > whether or not you did that manually.[/color]

                    It may be a bug in KWrite. As I entered it manually, I noticed that the
                    pasted text wasn't syntax highlighted.

                    Yeah, I know -- I should use a real editor, like vi or emacs ;-)

                    regards,
                    --
                    Leif Biberg Kristensen

                    Validare necesse est

                    Comment

                    • Leif B. Kristensen

                      #11
                      Re: String concatenation

                      Erik Max Francis wrote:
                      [color=blue]
                      > Maybe it's grabbing tabs, or obscure unprintable whitespace you can't
                      > see. Certainly what you're pasting in to these posts is intended,
                      > whether or not you did that manually.[/color]

                      The problem is recognised and confirmed. I posted a description of the
                      situation on comp.windows.x. kde, and received essentially this answer:

                      "you will notice that the "space" is an ASCII space (20 hex) in the
                      working version and ASCII space + 128 (A0 hex) in the non-working
                      version. Just because the display looks the same does not mean it is
                      the same."

                      regards,
                      --
                      Leif Biberg Kristensen

                      Validare necesse est

                      Comment

                      • Leif B. Kristensen

                        #12
                        Re: String concatenation

                        The "feature" is also submitted to the KDE bugtrack, see
                        <url:http://bugs.kde.org/show_bug.cgi?id =60971>.

                        Apparently, "real programmers" don't cut and paste code samples from
                        KNode. Go figure.

                        regards,
                        --
                        Leif Biberg Kristensen

                        Validare necesse est

                        Comment

                        • Peter Otten

                          #13
                          Re: String concatenation

                          Leif B. Kristensen wrote:
                          [color=blue]
                          > The "feature" is also submitted to the KDE bugtrack, see
                          > <url:http://bugs.kde.org/show_bug.cgi?id =60971>.
                          >
                          > Apparently, "real programmers" don't cut and paste code samples from
                          > KNode. Go figure.[/color]

                          I doubt that KNode is to blame. The problem you encountered occured
                          to me only sporadically. Therefore I guess that the culprit is elsewhere in
                          the toolchain.

                          In the meantime, whenever an apparent whitespace generates a syntax error:

                          <clean160.py>
                          #!/usr/bin/env python
                          import string, sys, os

                          transTable = string.maketran s(chr(160), " ")

                          if __name__ == "__main__":
                          for filename in sys.argv[1:]:
                          s = file(filename). read()
                          if chr(160) in s:
                          print "cleaning", filename
                          os.rename(filen ame, filename + ".160")
                          file(filename, "w").write(s.tr anslate(transTa ble))
                          else:
                          print "skipping", filename
                          <clean160.py>

                          Peter

                          PS: I'm not sure if the above reaches you without those vicious blanks, but
                          I'm confident :-)

                          Comment

                          • Leif B. Kristensen

                            #14
                            Re: String concatenation

                            Paul Rubin wrote:
                            [color=blue]
                            > tmp = [x for x in res if x and x[0] != '-']
                            > return ', '.join(tmp)[/color]

                            Substituting tmp with the real thing, it turns into a one-liner:

                            return ', '.join([x for x in res if x and x[0] != '-'])

                            Awesome :-)
                            --
                            Leif Biberg Kristensen

                            Validare necesse est

                            Comment

                            • Paul Rubin

                              #15
                              Re: String concatenation

                              "Leif B. Kristensen" <junkmail@solum slekt.org> writes:[color=blue][color=green]
                              > > tmp = [x for x in res if x and x[0] != '-']
                              > > return ', '.join(tmp)[/color]
                              >
                              > Substituting tmp with the real thing, it turns into a one-liner:
                              >
                              > return ', '.join([x for x in res if x and x[0] != '-'])
                              >
                              > Awesome :-)[/color]

                              Yeah, I wrote it that way at first, but figured it was obscure enough
                              already if you weren't used to list comprehensions, so I put back the
                              tmp variable.

                              Comment

                              Working...