Beginner Codes/Python/Format Specifiers
18%

Instructions

Syntax

f"{variable:.2f}"

Format Specifiers (Deep Dive) 🔬

f-strings use panni variables-a print panrathu epdi nu pathom. Aana andha variables-a innum 'style' ah print panna Format Specifiers use aagum. Idhu oru photo-ku filter podra madhiri dhaan!

The Magic Wand: : (Colon)

Oru variable kulla irukka value-a format panna, f-string kulla oru colon : vekkanum. Colon-ku aprm varadhu dhaan unga "Format Specifier".

1. Decimal Places (Pulliku aprm evlo numbers?) 🔢

Oru calculation-la periya number varudhu: 3.14159265... Adha just 2 decimal places-ku round pannanum na :.2f use pannalam.

Idhu epdi work aagudhu?

  • . -> "Naan decimals pathi pesa poren" nu sollam.
  • 2 -> "Enaku 2 decimal places dhaan venum".
  • f -> "Idhu oru Float (decimal number)".
pi = 3.14159265
print(f"Pi value is {pi:.2f}") # Output: 3.14
print(f"Pi value is {pi:.4f}") # Output: 3.1416

2. Large Numbers with Commas (Koma pottu ezhudhalam) 💰

Lakhs and Crores-a read panna kashtama iruka? , (comma) use panna thaanaave number-la comma vandhudum!

price = 1000000
print(f"Car price is {price:,}") # Output: 1,000,000

(Note: Python US format padi 3 zero-ku oru comma podum).

3. Combining Them (Rendayum serthu use panlam!) 🤝

Decimal-um venum, comma-vum venum na? Rendayum serthu ezudhalam! Syntax: :,.2f Modhalla comma ,, aprm decimal .2f.

bank_balance = 1250000.876
print(f"Balance: ${bank_balance:,.2f}") 
# Output: Balance: $1,250,000.88

4. Padding and Alignment (Space viduradhu) 📏

Oru text-a table madhiri neat-a align pannanum na:

  • < : Left align (Left pakkam thallidum)
  • > : Right align (Right pakkam thallidum)
  • ^ : Center align (Naduvula vekkum)
name = "Python"
print(f"|{name:>10}|") # Right align in 10 spaces -> |    Python|
print(f"|{name:^10}|") # Center align in 10 spaces-> |  Python  |

Oru Chinna Task!

Kizhe oru variable bill_amount = 45000.758 nu irukku. Idha f-string & format specifier use panni:

  1. Comma varanum (thousands separator).
  2. Exactly 2 decimal places dhaan varanum.
  3. Output exactly Total Bill: $45,000.76 nu print aaganum.

Help

Format SpecifiersExercise 15/7715 XP
❴❵ script.py
python.code
python
Loading...
Terminal
Terminal — python
Beginner Codes Terminal v1.0.0
─────────────────────────────────────
Ready. Click "Run Code" to execute...
Ready
Piston APIPYTHON0 lines