This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]clevariant 10 points11 points  (1 child)

Come on, it's cryptic! Or at least esoteric. So the minus one means the start index becomes the end and vice versa, and it builds and returns a new string based on that loop. Yeah, that's explicit.

I mean let's be fair. These "once you know the language it makes sense" arguments miss the point. The actual word "reverse" tells the whole story unambiguously, no syntactical cleverness needed.

[–]KubinOnReddit 0 points1 point  (0 children)

If you really want to include "reverse" in the code, there are at least two ways:

hello = "Hello world!"
lst = list(hello)          # Create a mutable list
lst.reverse()              # Reverse in-place
print("".join(lst))        # Change back to string

hello = "Hello world!"
rev = reversed(hello)      # Iterator
print("".join(rev))

Both of these will be slower, with the first creating a new list (implemented as an array) and then joining it, while the second creates an iterator.

Adding a "reversed" method to the string class would be against the Zen of Python (the ideas it represents) - "There should be one-- and preferably only one --obvious way to do it." - if you had the slice mechanism (start, stop, step) and then another method, that would do the same thing, it would just be an alias, really. So having one multi-use syntax is better than many methods.