Python Built-in Methods

Earlier you learned about functions and built-in functions. One of the built-in function is print() function. In this article, you will learn about python built-in methods.

Advertisements

There are two types of methods in python. One that comes from python modules and built-in methods. The python module will have function definition which you can use after importing the module into the program.

Built-in Methods

For built-in methods, there is no need to import any module. The built-in methods are associated with python data types, because the data types themselves are objects.

For example, let us consider isdigit() method. The isdigit() method is part of string type. Use the .(dot) notation to access any method.

# declare a string
myString = "13445"
myString_2 = "Hello"
# check if the strings contains any digits
result = myString.isdigit()
# print result
print(result)
result = myString_2.isdigit()
# print result 
print(result)

The isdigit() method checks the string object and look for any non-digit character. If it finds one, then returns False.If each character is a digit, then, it will return True. The output of the above program is given below.

True
False

Consider another method associated with list object.

# create a list
myDrink = ["tea","coffee","milk"]
# append the list
myDrink.append("juice")
# print the updated list
print(myDrink)

In the above example, we have created a new list of beverages. We are using .append method to update the list. Therefore, different types of data types have different types of methods. Some return an integer, Boolean value, and some update the values.

Advertisements

Functions vs. Methods

As we mentioned earlier, that the function is declared above the of program and called to do some tasks. The method is function that is associated to a data type.

For method, you need to use the dot(.) notation to access it.

Can we replace the built-in method with a function ?

The answer is Yes.

Let us consider another example where we replace the isdigit() method with isDigit() function.

import string 
def isDigit(myStr):
    for character in myStr:
           if not character in string.digits:
                   return False
    return True
myStr = "32455"
print(isDigit(myStr))
print(myStr.isdigit())

In the above program, both isDigit() and isdigit() are same.

True
True

Only difference is that the isDigit() needs argument string, and isdigit() is from the string class where argument comes from the object of that string class.

Advertisements

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Exit mobile version