4
In Python, we have the method reverse
within 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
?
So I can also use this Slices to make substring?
– Wallace Maxters
Yes! For example, try
"blah"[1:3]
and"blah"[2:]
. Works with lists and many other things too.– hugomg
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.
– jsbueno