Revert a string and add method to native objects in Python

Asked

Viewed 2,699 times

4

In Python, we have the method reversewithin the List. It reverses the order of a list.

Example:

[1, 2, 3].reverse() // [3, 2, 1]

However this method is not present in a string.

example (Python):

myString = "The String"
myString.reverse() // AttributeError: 'str' object has no attribute 'reverse'

1 - How do I reverse this string up on Python?

Another issue is that in javascript, for example, we have the Prototype, where it is possible to add a method to a native language class.

Example (Javascript):

  String.prototype.hello = function() {
        return this.toString() +  " hello!";
    } 

    "teste".hello() // "teste hello!"

2 - Has a way to create a method directly in the String class of Python?

2 answers

5


The reverse of Python lists reverts to the list in place, changing the list values instead of creating a new list written inside out. Since Python strings are immutable, it doesn’t make much sense that they supply the Reverse method.

A concise way to reverse a Python string is by using Slices

>>> 'hello world'[::-1]
'dlrow olleh'

A Slice like "abcdefghijklm"[1:9:2] picks up the elements from position 1 to 9, from 2 to 2. The Slice [::-1], picks up the elements from start to finish, walking backwards.

As for the second question, I do not recommend trying to add methods to system classes as this can result in several undesirable things. For example, if two different modules of your system decide to add a method with the same name to a system class one module will overwrite the work of the other. I prefer to define my auxiliary functions as normal functions in a module rather than as methods.

  • So I can also use this Slices to make substring?

  • 2

    Yes! For example, try "blah"[1:3] and "blah"[2:]. Works with lists and many other things too.

  • 1

    In addition to not being recommended, as you well say,, the answer to the second question is: "no, it is not possible". It is possible to change classes from the standard Python library, but only in cases where they are written in pure Python. Native types as strings are written in C.

1

You can invert the string by converting it to list, for example:

str = "The String"
list = str.split() # list é ['The', 'String']
list.reverse() # list agora é ['String', 'The']

Or, if you want to reverse the characters, you do:

str = "The String"
str = str[::-1] # agora str é 'gnirtS ehT'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.