深度阅读

How to String Formatting Dollar Sign In Python

作者
作者
2023年08月22日
更新时间
7.44 分钟
阅读时间
0
阅读量

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”.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。