Method for reversing strings

No worries here :smiley:

Wow… thanks very much for providing this insight!

reverse() clearly reads as a method, while reversed feels more like a property.

That said, this proposal is a step in the right direction for making Python more approachable to new and casual users. While [::-1] may seem straightforward to experienced developers, it can be confusing and less intuitive for beginners.

Adding a reverse() method is a dead end, though. Learning that teaches you nothing about anything else. Slicing is entirely general - not only does it work on things other than strings, but it also works with start and stop, or with a different step, or anything. Learning how slicing works gives you a whole new world of possibilities.

“Easy for beginners” isn’t necessarily the best for beginners. (And that’s even if we assume that “this string, but backwards” is even something that beginners need to do, which I’m not convinced of.)

5 Likes

Up until a few years ago the most useful information for a new developer was that stack overflow exists: How do I reverse a string in Python? - Stack Overflow

Of course, now it’s that AI exists and stack overflow exists when the AI hallucinates.

That wouldn’t work as you might expect. The details have already been explained in the posts above. I also appreciate how Python handles strings without overemphasizing string semantics, leaving that to the user.

s  = "👈🏾👆"
print(s[::-1])  # 👆🏾👈
print(len(s))  # 3
print(len(s.encode()))  # 12

for char in "👈🏾👆":
    print(char, ord(char))

for char in "👈🏾👆"[::-1]:
    print(char, ord(char))

Result:

👆🏾👈
3
12
👈 128072
🏾 127998
👆 128070
👆 128070
🏾 127998
👈 128072

But if a method to reverse strings were implemented, I would expect it to reverse them semantically—that is, to reverse the string while preserving its meaning. However, this could be unexpected for users who have been relying on [::-1] or reversed(). Also, wouldn’t fully reversing a string cause it to lose its meaning in many cases? What would the use case be for semantically reversing a string?

1 Like