Data Science · मराठी आवृत्ती · Python basics
P3.4 Python f-strings: Numbers, पैसे आणि Percentages format करा
हे का शिकायचं?
Report मध्ये 1234567.891 पेक्षा ₹12,34,567.89 वाचायला सोपं असतं.
हे काय आहे?
f-string म्हणजे f"..." — कंसातल्या {} मध्ये variable किंवा गणित लिहिता येतं. :,.2f commas आणि दोन दशांश देतो, :.1% percentage देतो.
कसं करायचं?
Step 1. Quotes आधी f लिहा.
Step 2. {} मध्ये variable लिहा.
Step 3. : नंतर format लिहा, उदा. :,.2f.
उदाहरणं: copy करा आणि चालवा
उदाहरण A: साधी f-string
हा code चालवा:
name = "Liam"
orders = 4
print(f"Hi {name}, you have {orders} orders.")
तुम्हाला दिसणारा output:
Hi Liam, you have 4 orders.
याचा अर्थ: {} मधल्या variables ची value text मध्ये आली.
उदाहरण B: Commas आणि दशांशांसह पैसे
हा code चालवा:
sales = 1234567.891
print(f"Sales: €{sales:,.2f}")
तुम्हाला दिसणारा output:
Sales: €1,234,567.89
याचा अर्थ: :,.2f ने हजारांचे commas आणि दोन दशांश आले.
उदाहरण C: Percentages
हा code चालवा:
rate = 45 / 60
print(f"Discharge rate: {rate:.1%}")
तुम्हाला दिसणारा output:
Discharge rate: 75.0%
याचा अर्थ: :.1% value ला 100 ने गुणून % लावतो.
उदाहरण D: Indian lakh पद्धत (छोटा helper)
हा code चालवा:
def inr(n):
s = str(int(n))
if len(s) <= 3:
return "₹" + s
last3 = s[-3:]
rest = s[:-3]
groups = []
while len(rest) > 2:
groups.insert(0, rest[-2:])
rest = rest[:-2]
if rest:
groups.insert(0, rest)
return "₹" + ",".join(groups) + "," + last3
print(inr(125450))
print(inr(12345678))
तुम्हाला दिसणारा output:
₹1,25,450
₹1,23,45,678
याचा अर्थ: Python चे commas western पद्धतीचे असतात. छोट्या function ने 12,34,567 असं lakh format मिळालं.