How to String Formatting Dollar Sign In Python

Published on Aug. 22, 2023, 12:16 p.m.

If you want to include a dollar sign in a Python string formatting expression, you can simply add the “$” symbol in the appropriate location within the format string. Here’s an example:

price = 9.99
formatted_price = "${:.2f}".format(price)
print(formatted_price)

This will output: “$9.99”. In the example above, the “{:.2f}” expression formats the “price” variable as a floating-point number with two decimal places. The “$” symbol is added before the formatted value to create a string with a dollar sign.

Alternatively, you can use f-strings in Python 3.6 and higher to format strings more easily. Here’s an example:

price = 9.99
formatted_price = f"${price:.2f}"
print(formatted_price)

This will output: “$9.99”.

Tags:

related content