1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Neat little python string trick

Discussion in 'Scripting & Programming' started by ffreeloader, May 26, 2008.

  1. ffreeloader

    ffreeloader Terabyte Poster

    3,661
    106
    167
    Python doesn't have a built-in method for reversing strings as strings are immutable in Python so how do you reverse the order of a string? It's really easy.

    Code:
    >>> alphabet
    'abcdefghijklmnopqrstuvwxyz'
    >>> tebahpla = alphabet[::-1]
    >>> tebahpla
    'zyxwvutsrqponmlkjihgfedcba'
    >>> 
    
    Yes, I know, very elementary, but really cool just the same because of its utter simplicity.

    I got this tip out of the "Object-Oriented Programming in Python" book.

    I've finally had a chance to go back to learning Python again and am having to refresh the basics because it's been so long since I had a chance to do anything with it. I'm one of those guys who has to be re-trained after lunch so when I get away from things for few months I'm really up a creek. :biggrin
     
    Certifications: MCSE, MCDBA, CCNA, A+
    WIP: LPIC 1
  2. tripwire45
    Honorary Member

    tripwire45 Zettabyte Poster

    13,493
    179
    287
    Python, python. How I miss thee...perhaps when I get the time...
     
    Certifications: A+ and Network+
  3. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    I'm currently trying my level best to avoid the language at work at the mo'. I like to code all this stuff for myself - silly, I know... :rolleyes:
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  4. ffreeloader

    ffreeloader Terabyte Poster

    3,661
    106
    167
    Been there, done that. Several times now.... :D
     
    Certifications: MCSE, MCDBA, CCNA, A+
    WIP: LPIC 1
  5. ffreeloader

    ffreeloader Terabyte Poster

    3,661
    106
    167
    I don't get it. You code all your own object methods from scratch? You never use any built-in methods in any language? It would seem to me that you would have to use some of them. All this does is take advantage of Python's ability to index and slice strings starting from the end of the string.
     
    Certifications: MCSE, MCDBA, CCNA, A+
    WIP: LPIC 1
  6. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    Yep, I prefer to do everything from scratch. I'm an algorithm efficiency whore in the sense that I like to perform tasks in the most efficient way possible, and this means doing it yourself for the task at hand.

    Let's take the Python method that you've demonstrated. Do you know which sorting algorithm it's using? My one gripe with Python is that all it cares about is getting things done, rather than getting them done efficiently. Don't worry, I get a lot of stick for my opinions at work as well. :)
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  7. ffreeloader

    ffreeloader Terabyte Poster

    3,661
    106
    167
    I wasn't giving you a hard time, I just didn't understand where you were coming from. I can see it, but don't know if it's worth the trouble for the kinds of projects I do. If I ever reach the level of doing really complicated stuff that requires a lot of efficiency to get things done I'd probably look at things the way you do. For now, I'll just stick with learning how do the simple stuff before I start trying to do the much more in-depth tasks. At my level of scripting tasks there's just not enough cycles to be saved to make a noticeable difference.
     
    Certifications: MCSE, MCDBA, CCNA, A+
    WIP: LPIC 1
  8. tripwire45
    Honorary Member

    tripwire45 Zettabyte Poster

    13,493
    179
    287
    LOL. Sorry. I got a visual image of that in my brain. Must be interesting evening wear. :biggrin
     
    Certifications: A+ and Network+
  9. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    I would link to the site for my 'evening wear', but fear that I'd be breaking forum rules! :biggrin
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  10. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    True, Freddie.

    Python was designed to code things up quickly to get things done. Maybe I'm expecting too much from it. :)
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  11. hbroomhall

    hbroomhall Petabyte Poster Gold Member

    6,623
    115
    224
    Why would you need a sorting algorithm to reverse a string?

    Harry.
     
    Certifications: ECDL A+ Network+ i-Net+
    WIP: Server+
  12. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    You're right. All you do is 'invert the index' to get the new index value in reverse order:
    Code:
        invIndex = 25 - index    # Where 'index is in range 0 - 25 inclusive.
    
    Apply the above formula to Freddie's alphabet string for the index to appear in reverse order. You're quite right as this is not a sort.

    Where the sorting is applied is when Freddie does
    Code:
        tebahpla = alphabet[::-1]
    
    which actually stores the aphabet in reverse order with updated indices, so instead of tebahpla[0] being 'a' it is now 'z'.
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  13. ffreeloader

    ffreeloader Terabyte Poster

    3,661
    106
    167
    I'm not sure I understand what you're saying. What I see happening with this is Python creates the new string by simply indexing the old string in reverse order. It takes the alphabet [-1] "z" and places it in the new string in tebahpla[0] then goes back to alphabet[-1] again which is now "y" and places it in tebahpla [1] and so on. alphabet and tebahpla are completely separate objects. "a" never did exist as tebahpla[0].

    As strings are immutable in Python you cannot change/update the indices of an existing string. You have to create a new string. Simply put Python is just reading the existing string from back to front and creating a new string at the same time.
     
    Certifications: MCSE, MCDBA, CCNA, A+
    WIP: LPIC 1
  14. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    When you use a sorting algorithm there is a best and a worst case. The best case is when the elements are already in order, and the worst case is when they are randomised to such an extent that every element must be moved from one location to another depending on some sorting criteria. The transition from the alphabet string to the tebahpla string is a fairly ideal case since the alphabet string is sorted, and the sorting algorithm is as per the formula that I gave above

    The actual act of sorting 'alphabet' into 'tebahpla' is thus:

    Criteria: That 'tebahpla' be the string 'alphabet' in reverse.
    Sorting algorithm: invIndex = 25 - index

    Or as a diagram:

    'alphabet' -> sort() -> 'tebahpla'

    Aha! This is what the syntax tells you Python is doing, but is that what is really going on under the hood?

    Remember that when invoking 'alphabet[::-1]' you are using a simple case for a complex mechanism. What about if you do

    alphabet[12:20:-1]
    alphabet[20:12:-1]
    alphabet[-12:20:-1]
    alphabet[20:-12:-1]
    etc. (Not sure if these would work, but illustrate issues none-the-less)

    Do you still believe that the underlying algorithm is as strightforward as reading the string backwards? :)
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  15. ffreeloader

    ffreeloader Terabyte Poster

    3,661
    106
    167
    Yes.

    Here's why:

    Code:
    >>> alphabet[0::-1]
    'a'
    >>> alphabet[::-2]
    'zxvtrpnljhfdb'
    >>> alphabet[25::-1]
    'zyxwvutsrqponmlkjihgfedcba'
    >>> alphabet[24::-1]
    'yxwvutsrqponmlkjihgfedcba'
    >>> alphabet[24:1:-1]
    'yxwvutsrqponmlkjihgfedc'
    >>> alphabet[23:2:-3]
    'xurolif'
    
    By placing the lower bound equal to the length of the string and omitting the upper bound we get exactly the same results as Python is stepping backwards through the string. If we place an upper bound of [0] or greater Python will step backwards to, but not include, that index. If we place a lower bound less than the length of the string Python will start there and step backwards until it reaches either the upper bound or the end of the string. If we increase the step we get exactly what we would expect.

    The [::-1} slicing of the string works with any string because it removes both the upper and lower bounds of the string and just allows Python to step backwards through the string regardless of its length.
     
    Certifications: MCSE, MCDBA, CCNA, A+
    WIP: LPIC 1
  16. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    Now, your explanation is a lot more complicated than the previous one you gave of Python simply 'reversing the order of the string'. The fact that it is so flexible in how you can present these immutable strings goes far beyond a simple algorithm. Feel free to implement the above in your chosen language to see what I'm getting at. The reason why Python is so flexible is because it hides complicated implementations that the user would otherwise be forced to implement; Python simple provides interfaces to more complex functionality. The details of the implementation of this functionality is hidden from the user.

    This is my whole point! :biggrin
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  17. ffreeloader

    ffreeloader Terabyte Poster

    3,661
    106
    167
    You may be right, I don't know. All I know is that in every Python book I have this is explained as Python stepping through a sequence. I've never even seen anyone else even suggest that it is anything more complex than that. Why it would be made more complex than that behind the scenes doesn't even make sense to me. I mean, stepping backwards, or forwards, through a sequence isn't rocket science.

    I can certainly appreciate that Python does hide a lot of complexity, but it doesn't make sense that someone smart enough to create their own programming language would be dumb enough to do something very simple in a manner many times harder than what it needs to be to work with a data type as simple as a consecutive sequence of characters.

    I could be wrong, but what you're suggesting says programmers, and the Python creators specifically, have very little common sense about how to solve a problem. I just find that hard to swallow.
     
    Certifications: MCSE, MCDBA, CCNA, A+
    WIP: LPIC 1
  18. mgoldwasser

    mgoldwasser New Member

    6
    2
    2

    Although I might not use as colorful terminology as you did earlier, I too am very devoted to algorithm efficiency. That said, I do not understand why you would be up in arms about this particular example. It is a straightforward behavior which is a linear-time pass through the sequence. If you wanted to do this yourself in a language such as C/C++/Java, it would be a simple loop framed as for (i=start; i<stop; i += step) if a positive stepsize or for (i=start; i>stop; i += step) if a negative step size. Nothing fancy here.

    As to the more general issue that you raise, there is indeed more complex functionality encapsulated within the standard libraries for Python (as well as for most other programming languages). Those implementations are typically well optimized and more efficient than one would do if rewriting it from scratch, unless you are taking advantage of some known qualities that makes your particular scenario different from the general one. Furthermore, those Python libraries are implemented directly in C and so more efficient then if you wrote your own interpretted Python code.

    If you are really interested, the implementation details for Python are not hidden. Python is an open source language. The entire implementation is available as a subversion project at http://svn.python.org. BTW, if you are interested in Python's sorting algorithm (although sorting was not relevant to this original thread), please see http://svn.python.org/projects/python/trunk/Objects/listsort.txt
     
  19. ffreeloader

    ffreeloader Terabyte Poster

    3,661
    106
    167
    mgoldwasser,

    Maybe you could answer another question I've come up with.

    I was looking for how to convert a string to a tuple and a tuple to string on Google and found a whole bunch of rather involved explanations in how to do this. What I did was the following working off the same string we've been using as an example in this thread.

    alphabet = (alphabet,) # Converts the string to a one element tuple
    alphabet = (alphabet[0]) #Converts the tuple back to the original string

    As I'm learning how to use scripting and programming languages one of the things I always try to keep in mind is the consequences of what my usage of the language might be further on down the line. So, what might be the security implications of doing these conversions this way, and when would be the time to validate the data on converting a tuple to a string? It looks to be easiest when it's a string but I'm unsure.
     
    Certifications: MCSE, MCDBA, CCNA, A+
    WIP: LPIC 1
  20. ffreeloader

    ffreeloader Terabyte Poster

    3,661
    106
    167
    One more thing.... You must have one heck of a bot out searching net to find mentions of your book. Every time I've mentioned it here or discussed what I've found in it you've been here very shortly thereafter....

    I'm impressed both by the speed of your finding my posts and with your support for your own book.
     
    Certifications: MCSE, MCDBA, CCNA, A+
    WIP: LPIC 1

Share This Page

Loading...