What is $ in Python?

The dollar $ operator in Python is quite similar to the Python f-string. Any variable prefixed with the dollar sign operator ($) in a string acts as a placeholder or an indicator for a substitute.

It is used for string formatting along with the string template class. The string is given as a parameter to the Template class constructor and the value to be substituted is declared in the substitute() function.

Below are some of the examples by which we can use the dollar operator in Python:

Using substitute() Function

In this example, we will see how $ in Python string acts as a placeholder. Here, we are using the substitute() function to replace the dollars written with the letter inside the function.

Python
# import Template
from string import Template

# constructor call
myStr = Template("My name is $name and I am learning $lang")

# substitute method for replacing values
print(myStr.substitute(name="John", lang="Python"))

Output:

My name is John and I am learning Python

Using safe_substitute() Function

We can also use safe_substitute() function, which prevents from raising the KeyError in case a placeholder is not provided with the substitute value. In this example we will see how Python $ operator works with the safe_substitute()

Python
# import template
from string import Template

# constructor
myStr = Template(
    "My name is $name and I am $age years old. I am learning $lang")

# safe_substitute method for replacing values
print(myStr.safe_substitute(name="John", lang="Python"))

Output:

My name is John and I am $age years old. I am learning Python

What Does $ Mean in Python?

Python programming language has several operators that are used to perform a specific operation on objects. These operators are special or special characters that perform a specific task, such as arithmetic operators, logical operators, assignment operators, etc. In this article, we will learn about another operator in Python which is used on Strings.

Similar Reads

What is $ in Python?

The dollar $ operator in Python is quite similar to the Python f-string. Any variable prefixed with the dollar sign operator ($) in a string acts as a placeholder or an indicator for a substitute....

Contact Us