Each data type has its own methods. In object-oriented programming (OOP), a method is a function that is associated with a class. In Python, everything is an object (or class, see chapter 6 for more on this topic), so every data type has its own methods because each type is defined as a class. Basically, think of a class as any object that has its own attributes and abilities. The abilities are the methods, the things we can do with the object. Another way of saying this is that the methods are the functions that are inherent to the object. They are ways of manipulating or interrogating the data type. The point here is that methods are not limited to data types. They are inherent to objects in general, but the methods for data types help us manipulate the data in a way that is specific to that data type.
For any method, we use the dot operator to access it. The syntax is object.method(). In the case of data types, the object is the data itself.
I will provide some basic examples of most important simple methods for each data type. These are not exhaustive lists, but they are the most commonly used methods that will be easy for beginners to understand the concepts associated with methods and types.
Note
You do not need to memorize all of these methods. They are here for reference. You will learn the most commonly used methods as you work with Python. The best way to learn is to practice using them in your own code.
String Methods
String methods are a good place to start because they are the most commonly used methods in Python. Strings are sequences of characters, and they have many methods that allow us to manipulate them. See the Python documentation for more information on strings. Here are some of the most commonly used string methods:
capitalize(): Converts the first character to upper case
casefold(): Converts string into lower case
center(): Returns a centered string
count(): Returns the number of times a specified value occurs in a string
length(): Returns the length of a string
index(): Searches the string for a specified value and returns the position of where it was found first. Note that indexes are 0-based numbers, so the first location is location 0.
string1="hello, world!"print('capitalize(): ', string1.capitalize())print('casefold(): ', string1.casefold())print('center(): ', string1.center(20))print('count(): ', string1.count('l'))print('length(): ', len(string1))# index will return 2 because the h is at index 0 and the e is at index 1print('index(): ', string1.index('l'))
len(string): Returns the length of the string. Example: "something" → 9.
string.count("s"): Counts the occurrences of a specific character in the string. Example: "something" → 1.
min(string): Returns the smallest character in the string (based on ASCII value). Example: "something" → "e".
max(string): Returns the largest character in the string (based on ASCII value). Example: "something" → "t".
"some" * 3: Repeats the string "some" three times. Example: "some" → "somesomesome".
first_name ="Nathan"last_name ="Michalewicz"print("Length of first name is", len(first_name))print("Count of 'a' in first name is", first_name.count("a"))print("Min of first name is", min(first_name))print("Max of first name is", max(first_name))print("first name * 3 is", first_name *3)
Length of first name is 6
Count of 'a' in first name is 2
Min of first name is N
Max of first name is t
first name * 3 is NathanNathanNathan
Methods for Splitting and Joining Strings
string.join(iterable): Combines elements of an iterable (e.g., a list) into a single string, using the specified string as a separator.
Example: " ".join(["a", "b", "c"]) → "a b c".
Explanation: The " " acts as the separator, joining the elements of the list into a single string with spaces between them.
string.partition(substring): Splits the string into three parts: the part before the first occurrence of the substring, the substring itself, and the part after it.
Explanation: This method is helpful for processing multi-line strings, as it automatically handles different types of line breaks.
lname ="Michalewicz"fname ="Nathan"s ="a b c d e f g"lines ="a\nb\nc\nd\ne\nf\ng"# \n is a newline characterprint(fname.partition("a"))print(fname.rpartition("a"))print(s.split(" ", 3))print(s.rsplit(" ", 3))print(lines.splitlines())
('N', 'a', 'than')
('Nath', 'a', 'n')
['a', 'b', 'c', 'd e f g']
['a b c d', 'e', 'f', 'g']
['a', 'b', 'c', 'd', 'e', 'f', 'g']
String Alignment and Padding methods
We can manipulate the padding and alignment of strings through a number of methods. Here are a few.
string.ljust(width): Left-aligns the string within a field of the specified width, padding the right side with spaces.
Example: "a".ljust(10) → "a ".
string.rjust(width): Right-aligns the string within a field of the specified width, padding the left side with spaces.
Example: "a".rjust(10) → " a".
string.center(width): Centers the string within a field of the specified width, padding both sides with spaces.
Example: "a".center(10) → " a ".
string.zfill(width): Pads the string with zeros on the left until it reaches the specified width.
Example: "a".zfill(10) → "000000000a".
string.center(width, fillchar): Centers the string within a field of the specified width, padding both sides with the specified fillchar.
Example: "a".center(10, "-") → "----a-----".
string.expandtabs(tabsize): Replaces tab characters (\t) in the string with spaces, using the specified tabsize for the width of each tab.
Example: "a\tb".expandtabs(10) → "a b".
string.strip(): Removes leading and trailing whitespace (or specified characters) from the string.
Example: " a ".strip() → "a".
string.lstrip(): Removes leading whitespace (or specified characters) from the string.
Example: " a ".lstrip() → "a ".
string.rstrip(): Removes trailing whitespace (or specified characters) from the string.
Example: " a ".rstrip() → " a".
s ="a"print("ljust", s.ljust(10))print("rjust", s.rjust(10))print("center", s.center(10))print("zfill", s.zfill(10))print("center", s.center(10, "-"))print("expandtabs", "a\tb".expandtabs(10))print(".strip", " a ".strip())print(".lstrip", " a ".lstrip())print(".rstrip", " a ".rstrip())
ljust a
rjust a
center a
zfill 000000000a
center ----a-----
expandtabs a b
.strip a
.lstrip a
.rstrip a
Find/Replace Methods
Strings have several methods for finding and replacing substrings. These methods are useful for searching for specific characters or patterns within a string and replacing them with other characters or strings.
string.find(substring): Searches for the first occurrence of the specified substring in the string and returns its lowest index. Returns -1 if the substring is not found.
Example: "something".find("s") → 0.
string.rfind(substring): Searches for the last occurrence of the specified substring in the string and returns its highest index. Returns -1 if the substring is not found.
Example: "something".rfind("s") → 0.
string.index(substring): Searches for the first occurrence of the specified substring in the string and returns its lowest index. Raises a ValueError if the substring is not found.
Example: "something".index("s") → 0.
string.rindex(substring): Searches for the last occurrence of the specified substring in the string and returns its highest index. Raises a ValueError if the substring is not found.
Example: "something".rindex("s") → 0.
string.replace(old, new): Replaces all occurrences of the old substring with the new substring in the string.
Input validation is a way to ensure that the input (or data)is in the correct data type. This is especially important when accepting user input. There are many ways to validate input. The most common way is to use the is functions. These functions are built into Python and return a boolean value.
The typical process is to accept an input value validate its type and then process it. If the input is not correct, you can raise an error or ask the user to input the correct value. If you try to process the input data before validating it, you may get an error, and errors stop the program because Python reads synchronously from top to bottom. That means the program will stop completely.
Below, you can see the different is functions that are available in Python.
Input Validation
Definition
str.isalpha()
True if all alphabetic
str.isdigit()
True if all digits
str.isalnum()
True if all alphanumeric
str.isdecimal()
True if all 0-9
str.isnumeric()
True if all numeric
str.islower()
True if all lowercase
str.isupper()
True if all uppercase
Some of these are self-explanatory, others are less clearly named. Naming is very important in Python, and you should take naming conventions seriously. Some of these are exemplary as to why. For example, isalpha() is a very clear name. It is easy to understand that it checks if the string is alphabetic. However, isdecimal() is less clear. Conventional English would indicate that this tests if the string includes a float or a decimal such as 2.0. But that is not the case. If it were, it would be named isfloat() (which doesn’t exist because the period will always be evaluated as non-numeric). Instead, isdecimal() checks if the string is a decimal number, such as 2 or 90. It checks if all the characters are numbers (0-9) without any other type of character.
Working with Integers and Floats
Numbers, while an object, typically do not have methods associated with them. Instead, they have functions that can be applied to them.
Mathematical Operators
Operator
Name
Example
+
Addition
1 + 2 outputs 3
-
Subtraction
2 - 1 outputs 1
*
Multiplication
2 * 2 outputs 4
/
Division
4 / 2 outputs 2
%
Modulus: takes the remainder of the first number divided by the second
9 % 2 outputs 1
**
Exponentiation: raises the first number to the power of the second
4 ** 2 outputs 16
Addition, subtraction, multiplication, and division are straightforward. The other two are a little different. The modulus operator returns the remainder of the division of the first number by the second. This can be helpful to find out if a number is divisible by another. The exponentiation operator raises the first number to the power of the second number.
Built-in Number Functions
Python provides several built-in functions that can be applied to numbers. These functions are not methods, but they are useful for performing mathematical operations on numbers.
abs(x): Returns the absolute value of x, which is the distance of x from zero, regardless of its sign.
Example: abs(-5) → 5.
max(x, y, z, ...): Returns the largest value among the provided arguments.
Example: max(1, 5, 3) → 5.
min(x, y, z, ...): Returns the smallest value among the provided arguments.
Example: min(1, 5, 3) → 1.
pow(x, y): Returns x raised to the power of y. Equivalent to x ** y.
Example: pow(2, 3) → 8.
round(x [, n]): Rounds x to the nearest integer. If n is specified, it rounds x to n decimal places.
There is also the math module, which provides additional mathematical functions. You need to import it to use it. The math module provides access to mathematical functions like trigonometric functions, logarithmic functions, and more advanced mathematical operations. They are not methods, but functions that can be applied to numbers.
import math
math.copysign(x, y): Returns x with the sign of y. This means the magnitude of x is preserved, but its sign is replaced with the sign of y.
Example: math.copysign(5, -3) → -5.
math.fabs(x): Returns the absolute value of x as a floating-point number.
Example: math.fabs(-5.5) → 5.5.
math.factorial(x): Returns the factorial of x, which is the product of all positive integers up to x. Only works for non-negative integers.
If you want more information on the math module, you can check the Python documentation.
List Methods
Similarly as strings, lists have methods that allow us to manipulate the data in the list. See the Python documentation for more information on lists. These are but a few of the most commonly used methods for lists.
append(): Adds an element at the end of the list
clear(): Removes all the elements from the list
copy(): Returns a copy of the list
count(): Returns the number of elements with the specified value
extend(): Add the elements of a list (or any iterable), to the end of the current list
index(): Returns the index of the first element with the specified value
insert(): Adds an element at the specified position
pop(): Removes the element at the specified position
remove(): Removes the first item with the specified value
The del statement is not a method, but it is a way to remove an element from a list. It can be used to delete an element at a specific index or to delete the entire list. Unlike pop(), del does not return the removed element. It simply removes it from the list. The del statement can also be used to delete entire lists or slices of lists following typical Python slicing syntax.
list1 = ["apple", "banana", "cherry"]del list1[1] # Deletes the element at index 1print("After del: ", list1) del list1[:] # Deletes all items in the listprint("After del list1: ", list1)
After del: ['apple', 'cherry']
After del list1: []
Tuples are immutable sequences, meaning that once they are created, their elements cannot be changed. This characteristic minimizes the number of methods available to them, but they do have a few methods that allow us to work with them.
count(): Returns the number of times a specified value occurs in a tuple.
index(): Searches the tuple for a specified value and returns the position of where it was found first. Note that indexes are 0-based numbers, so the first location is location 0.
Sets are unordered collections of unique elements. They have methods that allow us to perform set operations like union, intersection, and difference. See the Python documentation for more information on sets. Some of the most commonly used methods for sets are:
add(): Adds an element to the set
clear(): Removes all elements from the set
copy(): Returns a shallow copy of the set
difference(): Returns a set containing the difference between two or more sets
difference_update(): Removes the elements of another set from the current set
discard(): Removes an element from the set if it is a member. If not a member, it does nothing
intersection(): Returns a set containing the intersection of two or more sets.
intersection_update(): Updates the current set to be the intersection of itself and another set
isdisjoint(): Returns True if two sets have a null intersection (i.e., no common elements)
issubset(): Returns True if the current set is a subset of another set.
Dictionaries are unordered collections of key-value pairs. They have methods that allow us to manipulate the data in the dictionary. See the Python documentation for more information on dictionaries. Some of the most commonly used methods for dictionaries are:
clear(): Removes all elements from the dictionary
copy(): Returns a shallow copy of the dictionary
get(): Returns the value for a specified key if it exists, otherwise returns None or a specified default value if provided as the second argument.
items(): Returns a view object that displays a list of a dictionary’s key-value tuple pairs.
keys(): Returns a view object that displays a list of all the keys in the dictionary.
values(): Returns a view object that displays a list of all the values in the dictionary.
pop(): Removes the specified key and returns the corresponding value. Raises a KeyError if the key does not exist.
popitem(): Removes and returns the last inserted key-value pair as a tuple. If the dictionary is empty, it raises a KeyError.
dict1 = {"name": "Nathan", "age": 30, "city": "New York"}print("copy(): ", dict1.copy())print("get(): ", dict1.get("name"))print("items(): ", dict1.items())print("keys(): ", dict1.keys())print("values(): ", dict1.values())print("pop(): ", dict1.pop("age")) # Removes 'age' key and returns its valueprint("popitem(): ", dict1.popitem()) # Removes and returns the last inserted key-value pairprint("updated dict1 from pop and popitem(): ", dict1)print("clear(): ", dict1.clear())
Notice that the pop() method removes a specified key and returns the removed item, while popitem() removes the last inserted key-value pair (and also returning it). This is useful when you want to remove an item without knowing its key.
Random Functions
Python also provides a random module that allows you to generate random numbers and perform random operations. This is particularly useful in data analytics for tasks like sampling, shuffling data, or generating random test cases. The random module includes various functions to generate random numbers, shuffle lists, and set seeds for reproducibility.
random.choice(iter): Selects and returns a random element from the given iterable (e.g., a list or tuple).
random.seed(x): Sets the seed for the random number generator, ensuring reproducible results. In other words, if you set the seed of the random generator, the sequence of randomly generated numbers will always be the same. This is true regardless of when or where the code is run as long as the seed is set the same. This allows you to recreate the same random behavior consistently.
Example: random.seed(42) → Subsequent random calls will produce the same sequence of values.