· Hakan Çelik · Python · 4 dk okuma
String Methods and Method Operations (Method, Method-Wrapper)

String Methods and Method Operations (Method, Method-Wrapper)
str Object Methods and Method Operations (Method, Method-Wrapper)
Introduction
In previous articles we introduced Python and functions, learned to use a few functions, touched on types, and examined conditional statements. Now we will tackle a much larger and more interesting topic. We previously learned that everything in Python is an object and we got to know the str type — let us now dive a little deeper together.
What is a Method?
Methods are functions that belong to a class (object).
What is a Method-Wrapper?
Method-wrappers are themselves methods, defined at the C level for built-in objects, that make certain operations faster.
The wrappers covered here exist on every object defined in Python. I am progressing through the str object in this article, but it is worth noting that they are universal.
Python is written in C.
We generally use these methods without realising it. For example:
>>> "string" <= "string"
>>> "1" == "1"These operations are carried out by method-wrappers.
Method-Wrappers
Understanding wrappers matters for object-oriented programming (OOP) because once we know them we can override them in our own classes.
__ne__ — Not-Equal-To Operation Method
Open the Python console and type one of the following:
"".__ne__str('').__ne__"test".__ne__
You will see output similar to <method-wrapper '__ne__' of str object at 0x0000024D27BB7C70>, confirming that __ne__ on a str object is a method-wrapper.
What does __ne__ do and how is it used?
>>> "".__ne__.__doc__
'Return self!=value.'It returns True if the object (self) is not equal to the given value.
>>> "".__ne__("") # same value → False
False
>>> "1".__ne__("") # different values → True
TrueThe same operation written the normal way:
>>> "" != ""
False
>>> "1" != ""
True__mul__ — Multiplication Operation Method
>>> str(1).__mul__.__doc__
'Return self*value.'It multiplies the string by the given value:
>>> str(1).__mul__(3)
'111'
>>> str("-").__mul__(13)
'-------------'The familiar shorthand:
>>> "-" * 13
'-------------'Python uses this wrapper internally. You can even change the result of "-" * 30 by overriding __mul__ in a subclass:
class TStr(str):
def __mul__(self, times):
return times # return the multiplier instead of repeating the string
test_str = TStr("this is a test class")
print(test_str * 3) # outputs: 3__lt__ — Less-Than Operation Method
>>> "".__lt__.__doc__
'Return self<value.'>>> "".__lt__("123")
True
>>> "" < "123"
TrueYou can override __lt__ in a custom class:
class MyStrClass(str):
def __lt__(self, text):
return text # return the right-hand operand instead of a bool
my_str = MyStrClass("my str object")
print(my_str < "test string")
# output: 'test string'__len__ — Length Operation
>>> "".__len__.__doc__
'Return len(self).'Works exactly like the built-in len() function:
>>> "33".__len__()
2
>>> [1, 2, 3].__len__()
3__le__ — Less-Than-or-Equal-To Operation
>>> "".__le__.__doc__
'Return self<=value.'>>> "test a".__le__("test a")
True
>>> "test a e".__le__("test a")
False__eq__ — Equality Operation
>>> "hakan".__eq__("hakan")
True
>>> "hakan celik".__eq__("hakan")
False
>>> "hakan" == "hakan"
True__ge__ — Greater-Than-or-Equal-To Operation
Implements "hakan" >= "celik", or equivalently "hakan".__ge__("celik").
__gt__ — Greater-Than Operation
Implements "hakan" > "celik", or equivalently "hakan".__gt__("celik").
__iter__ — Iterator Operation
Turns the string into an iterator:
>>> for i in "test".__iter__():
... print(i)>>> for i in "test":
... print(i)Both examples do the same thing — we use __iter__ without realising it.
__init_subclass__
Runs when the class is subclassed. More information: PEP 487 — Simpler customisation of class creation
__new__
The first method called when an object is instantiated. The equivalent of a constructor in other languages.
__init__
Used to assign attributes when an object is instantiated.
Methods
swapcase()
Converts uppercase characters to lowercase and lowercase characters to uppercase.
>>> "AbCd ".swapcase()
'aBcD 'partition()
Splits the string into three parts using the given separator. Returns a 3-tuple.
>>> "1231 1".partition("2")
('1', '2', '31 1')
>>> "a".partition("a")
('', 'a', '')maketrans()
Takes a single dict parameter and is used together with translate() to replace characters.
>>> str().maketrans(dict(a=1))
{97: 1}translate()
Replaces each character in the string according to a translation table built with maketrans().
>>> "b".translate(str().maketrans(dict(b="r")))
'r'
>>> "bcca".translate(str().maketrans(dict(c="r")))
'brra'ljust()
Takes an integer parameter and pads the string with spaces on the right to reach that width.
>>> "Hakan".ljust(11)
'Hakan 'join()
Takes a list or tuple and inserts the string between each element.
>>> "/".join(["path", "to"])
'path/to'istitle()
Returns True if the string is in title case.
>>> "This Is A Title".istitle()
True
>>> "This is a title".istitle()
Falseisspace()
Returns True if the string consists only of whitespace characters.
>>> str().isspace()
False
>>> str(" ").isspace()
Trueislower()
Returns True if all characters are lowercase.
>>> "Ab".islower()
False
>>> "ab".islower()
Trueisdecimal()
Returns True if all characters can be converted to a number.
>>> "1".isdecimal()
True
>>> "a 1".isdecimal()
False
>>> "1234".isdecimal()
Trueisascii()
Returns True if all characters are ASCII.
>>> "asd".isascii()
Trueisalpha()
Returns True if the string consists only of alphabetic characters.
>>> "asd".isalpha()
True
>>> "123".isalpha()
Falseisalnum()
Returns True if the string consists only of letters or numbers.
>>> "12s".isalnum()
True
>>> "test a".isalnum() # space → False
Falseindex()
Returns the index of the first occurrence of the given substring.
>>> "test a".index("a")
5expandtabs()
Expands tab escape characters (\t) into spaces. Default tab size is 8.
>>> "test \t".expandtabs()
'test 'count()
Returns how many times the given substring appears.
>>> "I love you 3000".count("0")
3center()
Centers the string within the given total width.
>>> "I do not feel good".center(30)
' I do not feel good '
Hakan Çelik

