Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I format both a string and variable in an f-string?

I'm trying to move both the "$" and totalTransactionCost to the right side of the field.

My current code is : print(f"Total Cost Of All Transactions: ${totalTransactionCost:>63,.2f}")

The code is able to move the totalTransactionCost to the right side of the field, but how can I include the "$" too?

like image 249
Carson McDowell Avatar asked Dec 14 '25 13:12

Carson McDowell


2 Answers

You can use nested f-strings, which basically divides formatting into two steps: first, format the number as a comma-separated two-decimal string, and attach the $, and then fill the whole string with leading spaces.

>>> totalTransactionCost = 10000
>>> print(f"Total Cost Of All Transactions: {f'${totalTransactionCost:,.2f}':>64}")
Total Cost Of All Transactions:                                                       $10,000.00
like image 160
Mechanic Pig Avatar answered Dec 16 '25 06:12

Mechanic Pig


f-string offers flexibility.
If the currency is determined by the system, locale allows leveraging the system's setting: LC_MONETARY for currency

Below is a f-string walkthrough

## input value or use default
totalTransactionCost = input('enter amount e.g 50000') or '50000'

## OP's code:
#print(f"Total Cost Of All Transactions: ${totalTransactionCost:>63,.2f}")

## f-string with formatting
## :,.2f  || use thousand separator with 2 decimal places
## :>63 || > aligns right with 63 spaces
## :<      || < aligns left
## { ... :,.2f} apply to inner f-string value
## {f'${ ... }':>64}  || apply to outer f-string value

print(f'|Total Cost of All Transactions|: {f"${int(totalTransactionCost):,.2f}":>64}')

## Note that the inner and outer uses different escapes. 
## The order doesn't matter though. Here, inner is " and outer is '.

|enter amount e.g 50000| 750000
Total Cost of All Transactions:                                                      $750,000.00
like image 39
semmyk-research Avatar answered Dec 16 '25 05:12

semmyk-research



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!