Python Common Helper Functions
2 min readFeb 14, 2023
Python is a popular programming language known for its simplicity and ease of use. It offers a wide range of libraries and functions that make programming more efficient and effective. In this article, we will cover 36 commonly used helper functions in Python and how they can be used to simplify your code.
String Manipulation:
str.replace()
- replaces a substring with another substring in a stringstr.upper()
- returns the uppercase version of a stringstr.lower()
- returns the lowercase version of a stringstr.strip()
- removes whitespace from the beginning and end of a stringstr.split()
- splits a string into a list of substrings based on a delimiterstr.join()
- concatenates a list of strings into a single string with a delimiterstr.startswith()
- checks if a string starts with a specific substringstr.endswith()
- checks if a string ends with a specific substringstr.find()
- returns the index of the first occurrence of a substring in a stringstr.count()
- returns the number of occurrences of a substring in a string
List Manipulation:
len()
- returns the length of a listlist.append()
- adds an item to the end of a listlist.extend()
- adds the elements of a list to another listlist.insert()
- inserts an item at a specific index in a listlist.pop()
- removes and returns the last item in a listlist.remove()
- removes the first occurrence of an item from a listlist.index()
- returns the index of the first occurrence of an item in a listlist.sort()
- sorts the items in a list in ascending orderlist.reverse()
- reverses the order of the items in a list
Math:
max()
- returns the maximum value in a list or set of valuesmin()
- returns the minimum value in a list or set of valuesabs()
- returns the absolute value of a numberround()
- rounds a number to a specified number of decimal placespow()
- raises a number to a specified powersum()
- returns the sum of all the values in a list or set of values
File I/O:
open()
- opens a file for reading or writingread()
- reads the contents of a filewrite()
- writes data to a fileclose()
- closes a filewith open()
- opens a file and automatically closes it when done
Datetime:
datetime.datetime.now()
- returns the current date and timedatetime.timedelta()
- creates a time durationstrftime()
- formats a datetime object as a string
Random:
random.randint()
- returns a random integer within a specified rangerandom.choice()
- returns a random item from a listrandom.shuffle()
- shuffles the items in a list in random order
Note: This is not an exhaustive list and there are many other helper functions available in Python for different purposes.