Revert a string and possibility of method addition on native objects in Python

3

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

Example:

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

But this method is not present in a string.

example (Python):

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

1 - How would I revert this string to Python ?

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

Example (Javascript):

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

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

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

    
asked by anonymous 13.01.2015 / 16:07

2 answers

5

The reverse of lists in Python reverts to the in place list, changing the list values instead of creating a new list written inside out. Because strings in Python are immutable, it does not make much sense for them to override the reverse method.

A concise way to reverse a string in Python is by using slice notation

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

A slice such as "abcdefghijklm" [1: 9: 2] takes elements from position 1 through 9, from 2 to 2. The slice [::-1] , takes elements from start to finish, walking back and forth .

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 resolve 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 helper functions as normal functions in a module itself rather than as methods.

    
13.01.2015 / 16:40
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 invert the characters, you do:

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