python · April 12, 2023 0

How to Write a decorator to add a ‘$’ sign to a number in Python

Table of Content

Certainly, here’s an example of a Python decorator that adds a ‘$’ sign to a number:

def add_dollar_sign(func):
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        return f'${result}'
    return wrapper

You can then apply this decorator to any function that returns a number, and it will add the ‘$’ sign to the result. For example:

def calculate_total_cost(price, quantity):
    return price * quantity

total_cost = calculate_total_cost(10, 5)
print(total_cost) # outputs "$50"

In this example, the add_dollar_sign decorator takes a function as an argument, defines a new function wrapper that calls the original function and adds a ‘$’ sign to the result, and finally returns the new function. The @add_dollar_sign syntax applies the decorator to the calculate_total_cost function, so that when it is called the result is automatically wrapped with the ‘$’ sign.

I hope this helps! Let me know if you have any more questions.

%d bloggers like this: