Retrieve a substring from the end in Python

To extract a substring in Python, use slicing. By specifying the start and end indices like string[start:stop], you can obtain a substring. By providing a negative index for the starting index, you can extract a substring from the end of the string.

Source Code


def substring_from_end(string, length):
    """
    Returns a substring of the specified length from the end of the string.

    Parameters:
    string (str): The original string from which the substring will be extracted. Returns an empty string if None.
    length (int): The length of the substring to extract.

    Returns:
    str: The substring extracted from the end of the string.
    """
    if string is None:
        return ""

    return string[-length:]

Example Results

# Example 1: When string is None
string = None
length = 3
substring = substring_from_end(string, length)
print(substring)  # Output: ""

# Example 2: Extracting the last 3 characters from the string "abcdef"
string = "abcdef"
length = 3
substring = substring_from_end(string, length)
print(substring)  # Output: "def"

Follow me!

photo by:Rubaitul Azad