invert or reverse a string... warning this is a rant

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • rick

    invert or reverse a string... warning this is a rant

    Why can't Python have a reverse() function/method like Ruby?

    Python:
    x = 'a_string'
    # Reverse the string
    print x[::-1]

    Ruby:
    x = 'a_string'
    # Reverse the string
    print x.reverse

    The Ruby approach makes sense to me as a human being. The Python
    approach is not easy for me (as a human being) to remember. Can that be
    changed or should I just start blindly memorizing this stuff?

    P.S. I like Python better than Ruby 90% of the time and use Python 90%
    of the time, but 10% of the time, little things such as this drive me crazy!
  • John Salerno

    #2
    Re: invert or reverse a string... warning this is a rant

    rick wrote:
    Why can't Python have a reverse() function/method like Ruby?
    I'm not steeped enough in daily programming to argue that it isn't
    necessary, but my question is why do you need to reverse strings? Is it
    something that happens often enough to warrant a method for it?

    Comment

    • Paul Rubin

      #3
      Re: invert or reverse a string... warning this is a rant

      rick <ath-admin@vt.eduwri tes:
      Why can't Python have a reverse() function/method like Ruby?
      >
      Python:
      x = 'a_string'
      # Reverse the string
      print x[::-1]
      >
      The Ruby approach makes sense to me as a human being. The Python
      approach is not easy for me (as a human being) to remember. Can that
      be changed or should I just start blindly memorizing this stuff?
      You could use:

      print ''.join(reverse d(x))

      That also looks a little bit weird, but it combines well-known Python
      idioms straightforward ly.

      Comment

      • Fredrik Lundh

        #4
        Re: invert or reverse a string... warning this is a rant

        rick wrote:
        The Ruby approach makes sense to me as a human being.
        do the humans on your planet spend a lot of time reversing strings?
        it's definitely not a very common thing to do over here.

        anyway, if you do this a lot, why not define a helper function?

        def reverse(s):
        return s[::-1]

        print reverse("redael ruoy ot em ekat")

        </F>

        Comment

        • Brad

          #5
          Re: invert or reverse a string... warning this is a rant

          John Salerno wrote:
          rick wrote:
          >Why can't Python have a reverse() function/method like Ruby?
          >
          I'm not steeped enough in daily programming to argue that it isn't
          necessary, but my question is why do you need to reverse strings? Is it
          something that happens often enough to warrant a method for it?
          I'm home for lunch so my email addy is different.

          No, it doesn't happen very often, but when I need to reverse something
          (usually a list or a string). I can never remember right of the top of
          my head how to do so in Python. I always have to Google for an answer or
          refer back to old code.

          IMO, I should be able to intuitively know how to do this. Python is so
          user-friendly most every place else... why can it not be so here?

          I wrote this so I'll never have to remember this again:

          def invert(invertab le_object):
          try:
          print invertable_obje ct[::-1]
          return invertable_obje ct[::-1]
          except:
          print 'Object not invertable'
          return 1

          invert([1,2,3,4])
          invert('string' )
          invert({1:2, 3:4})




          Comment

          • Neil Cerutti

            #6
            Re: invert or reverse a string... warning this is a rant

            On 2006-10-19, Brad <rtilley@vt.edu wrote:
            I'm home for lunch so my email addy is different.
            >
            No, it doesn't happen very often, but when I need to reverse
            something (usually a list or a string). I can never remember
            right of the top of my head how to do so in Python. I always
            have to Google for an answer or refer back to old code.
            >
            IMO, I should be able to intuitively know how to do this.
            Python is so user-friendly most every place else... why can it
            not be so here?
            >
            I wrote this so I'll never have to remember this again:
            >
            def invert(invertab le_object):
            try:
            print invertable_obje ct[::-1]
            return invertable_obje ct[::-1]
            except:
            print 'Object not invertable'
            return 1
            >
            invert([1,2,3,4])
            invert('string' )
            invert({1:2, 3:4})
            Shoot, now you'll have to remember where in heck you stashed that
            function the next time you need to reverse something. ;-)

            You'll still be better off in the long run memorizing the slice
            notation.

            --
            Neil Cerutti

            Comment

            • Brad

              #7
              Re: invert or reverse a string... warning this is a rant

              Fredrik Lundh wrote:
              rick wrote:
              >
              >The Ruby approach makes sense to me as a human being.
              >
              do the humans on your planet spend a lot of time reversing strings? it's
              definitely not a very common thing to do over here.
              On our planet, we're all dyslexic. We tend to do things 'backwards' so
              being able to easily invert what we do helps the people we show the code
              to on your planet make sense of it.
              >
              anyway, if you do this a lot, why not define a helper function?
              >
              def reverse(s):
              return s[::-1]
              >
              print reverse("redael ruoy ot em ekat")
              Thanks, that's what I ended up doing.

              Comment

              • James Stroud

                #8
                Re: invert or reverse a string... warning this is a rant

                John Salerno wrote:
                rick wrote:
                >
                >Why can't Python have a reverse() function/method like Ruby?
                >
                >
                I'm not steeped enough in daily programming to argue that it isn't
                necessary, but my question is why do you need to reverse strings?
                It would provide symmetry for reversing any sequence (without requiring
                an iterator).

                (1,2,3).reverse d()

                "123".reversed( )

                [1,2,3].reversed()



                --
                James Stroud
                UCLA-DOE Institute for Genomics and Proteomics
                Box 951570
                Los Angeles, CA 90095


                Comment

                • Paul Boddie

                  #9
                  Re: invert or reverse a string... warning this is a rant

                  James Stroud wrote:
                  >
                  It would provide symmetry for reversing any sequence (without requiring
                  an iterator).
                  >
                  (1,2,3).reverse d()
                  >
                  "123".reversed( )
                  >
                  [1,2,3].reversed()
                  That might infuriate those who regard strings as "mischievou s"
                  sequences (ie. things which cause errors because you think you have a
                  list, but you're actually accessing characters in a string), but it's a
                  valid point: the built-in sequence types should, within reason, provide
                  a similar interface.

                  The proposed solution involving slicing syntax does seem odd in the
                  sense that it's highly similar to the redundant-for-strings s[:]
                  operation, and it might require inspiration for anyone looking for
                  convenience methods on the string object to consider using slicing
                  instead in this manner. In looking for alternative approaches, I became
                  somewhat distracted by the classic approach you'd use with certain
                  functional languages: convert the string into a list of characters (if
                  it isn't already treated as a list), reverse the list, concatenate the
                  list. The following requires Python 2.4:

                  "".join(list(re versed(list(s)) ))

                  I guess Python 2.5 has the reversed method of which you speak. Still,
                  the simplest things are often the best, and Python's classic operators
                  (indexing, slicing) should always be kept in mind.

                  Paul

                  Comment

                  • James Stroud

                    #10
                    Re: invert or reverse a string... warning this is a rant

                    Paul Boddie wrote:
                    James Stroud wrote:
                    >>(1,2,3).rever sed()
                    >>
                    >>"123".reverse d()
                    >>
                    >>[1,2,3].reversed()
                    >
                    I guess Python 2.5 has the reversed method of which you speak.
                    Not that I could find (as methods of any built in sequence type). 2.5
                    just has the "reversed" function that returns and iterator and so 2.5
                    requires these kind of gymnastics on built in sequences:
                    "".join(list(re versed(list(s)) ))
                    Of course, I think str.join can operate on iterators, as Paul Rubin
                    suggests:
                    print ''.join(reverse d(x))
                    This latter approach still seems a little clunky, though.

                    James


                    --
                    James Stroud
                    UCLA-DOE Institute for Genomics and Proteomics
                    Box 951570
                    Los Angeles, CA 90095


                    Comment

                    • Ron Adam

                      #11
                      Re: invert or reverse a string... warning this is a rant

                      James Stroud wrote:
                      Of course, I think str.join can operate on iterators, as Paul Rubin
                      suggests:
                      >
                      print ''.join(reverse d(x))
                      >
                      This latter approach still seems a little clunky, though.
                      >
                      James
                      Slices can be named so you could do...
                      >>reverser = slice(None, None, -1)
                      >>>
                      >>'abcdefg'[reverser]
                      'gfedcba'


                      Ron

                      Comment

                      • Fredrik Lundh

                        #12
                        Re: invert or reverse a string... warning this is a rant

                        James Stroud wrote:
                        without requiring an iterator
                        can we perhaps invent some more arbitrary constraints while we're at it?

                        </F>

                        Comment

                        • James Stroud

                          #13
                          Re: invert or reverse a string... warning this is a rant

                          Fredrik Lundh wrote:
                          James Stroud wrote:
                          >
                          without requiring an iterator
                          >
                          can we perhaps invent some more arbitrary constraints while we're at it?
                          >
                          </F>
                          >
                          Why does it seem to me that you are confusing convienience with
                          constraint, or are the two equivalent?

                          James

                          --
                          James Stroud
                          UCLA-DOE Institute for Genomics and Proteomics
                          Box 951570
                          Los Angeles, CA 90095


                          Comment

                          • Neil Cerutti

                            #14
                            Re: invert or reverse a string... warning this is a rant

                            On 2006-10-19, Fredrik Lundh <fredrik@python ware.comwrote:
                            James Stroud wrote:
                            >
                            without requiring an iterator
                            >
                            can we perhaps invent some more arbitrary constraints while
                            we're at it?
                            No letter G. I don't like them. They wet their nests.

                            --
                            Neil Cerutti
                            You only get a once-in-a-lifetime opportunity so many times.
                            --Ike Taylor

                            Comment

                            • James Stroud

                              #15
                              Re: invert or reverse a string... warning this is a rant

                              Fredrik Lundh wrote:
                              James Stroud wrote:
                              >
                              without requiring an iterator
                              >
                              can we perhaps invent some more arbitrary constraints while we're at it?
                              >
                              </F>
                              >
                              I guess while I'm at it, this thread wouldn't have so much steam were
                              these idioms seemingly unpythonic:

                              "".join(reverse (x))
                              alist[::-1]

                              The latter, while more terse than alist.reversed( ), is unnatural and
                              ugly compared to the general elegance of other constructs in python.
                              Were this not the case, beginners and intermediate programmers alike
                              would not have such trouble remembering it. In fact, the latter's exact
                              behavior, if I remember correctly, spawned a thread of its own with much
                              speculation as to the exact meaning of the documentation and whether the
                              API conformed to this inferred meaning. I'll attempt to provide a link
                              to the thread if anyone takes me to task on this.

                              I'm sure many life-long programmers will claim that they have never
                              created a reverse copy of a data structure for production code, but why
                              is it that so many jump to the fore to point out that alist[::-1] is how
                              one produces a reverse copy of a list, or that a string can be reversed
                              with reversed, join, and an instance of another string (did I leave
                              something out?)?

                              But why do so many beginning programmers ask how one might produce a
                              reverse data structure in python? Perhaps they are just ignorant fools
                              who don't know that creating a reverse copy of a data structure can be
                              proven to be a useless operation if only they would stop trying to write
                              code and begin to write formal proofs. Perhaps their professors are to
                              blame, unreasonably asking them to write actual code before memorizing
                              all three+ volumes of Knuth. I'm sure the proof is in there somewhere.

                              But maybe it is not the purpose of a poweful language like python to be
                              used as a teaching language. Maybe python should be reserved for use
                              only by those who have been desensitized to its idiosyncracies,
                              inconsistencies , and idiomatic workarounds.

                              James

                              --
                              James Stroud
                              UCLA-DOE Institute for Genomics and Proteomics
                              Box 951570
                              Los Angeles, CA 90095


                              Comment

                              Working...