Home › Hindi › String Formatting Hindi में
Python String Formatting — f-string, .format() और %
🌐 यह page Hindi में है · String methods Hindi में पढ़ें →
f-string.format()% operatorDecimals और padding
तीन तरीके — कौन सा कब
Python में string formatting के तीन तरीके हैं। नया code हमेशा f-string से लिखो; बाकी दो पुराने code में मिलेंगे और उन्हें पहचानना ज़रूरी है।
name, score = "Asha", 91.5
# 1 — f-string (Python 3.6+) — यही लिखो
f"{name} scored {score}"
# 2 — .format() (Python 2.6+) — templates और logging में
"{} scored {}".format(name, score)
"{who} scored {what}".format(who=name, what=score)
# 3 — % operator (पुराना, C जैसा) — पुराने code में
"%s scored %.1f" % (name, score)
"%s scored %.1f" % {"n": name, "s": score} # dict के साथ
f-string — असली ताकत
f-string में आप सीधे Python expression लिख सकते हो, format spec colon के बाद जोड़ सकते हो, और nested quotes भी use कर सकते हो (Python 3.12+)।
items = ["a", "b", "c"]
f"{len(items)} items" # expression चलता है
f"{name.upper()}" # method call भी
f"{score / 100:.1%}" # 91.5%
f"{total:>10}" # right-align, 10 चौड़ा
f"{total:<10}|" # left-align
f"{total:^10}|" # center
f"{total:0>8}" # 00001234
f"{n:,}" # 1,234,567
f"{pi:.3f}" # 3.142
f"{n:#x}" # hex
f"{value!r}" # repr() — debugging के लिए
f"{'done' if ok else 'failed'}" # conditional
# debug के लिए सबसे काम का trick
f"{score=}" # score=91.5 — नाम और value दोनोंआखिरी line याद रख लो। f"{x=}" variable का नाम और value दोनों print करता है — debugging में बार-बार print(f"x={x}") लिखने की ज़रूरत खत्म।
Decimals, padding और alignment
Colon के बाद का हिस्सा format spec है। इसका आकार है [[fill]align][sign][#][0][width][,][.precision][type] — पर व्यवहार में इतना ही काफी है:
pi = 3.14159265
f"{pi:.2f}" # 3.14 — दो decimal
f"{pi:.0f}" # 3 — कोई decimal नहीं
f"{pi:.4f}" # 3.1416 — round होता है, truncate नहीं
f"{pi:>10.2f}|" # 3.14| — चौड़ाई 10, right-align
f"{pi:<10.2f}|" # 3.14 | — left-align
f"{pi:0>8.2f}|" # 00003.14| — 0 से भरना
f"{pi:,.2f}" # 3.14
# percent
f"{0.915:.1%}" # 91.5%
f"{91.5:.0f}%" # 91% — अगर value पहले से 100 से गुणा है
# integers
f"{1234567:,}" # 1,234,567
f"{255:#x}" # 0xff
f"{255:#b}" # 0b11111111
f"{5:03d}" # 005 — fixed-width codes के लिए
# .format() में बिल्कुल वही spec
"{:.2f}".format(pi) # 3.14
"{:>10}".format(name) # right-aligned
Table बनाना — असली use case
Formatting का सबसे काम का उपयोग साफ-सुथरा table print करना है। Fixed width columns से output पढ़ने लायक बन जाता है:
rows = [("Asha", 91.5), ("Ravi", 42.0), ("Meera", 77.25)]
print(f"{'Name':<10} {'Marks':>7}")
print("-" * 18)
for name, marks in rows:
print(f"{name:<10} {marks:>7.2f}")
# Name Marks
# ------------------
# Asha 91.50
# Ravi 42.00
# Meera 77.25
# चौड़ाई data से निकालना
w = max(len(n) for n, _ in rows)
for name, marks in rows:
print(f"{name:<{w}} {marks:>7.2f}") # nested field — चौड़ाई runtime परआखिरी line में {name:<{w}} ध्यान देने लायक है — चौड़ाई भी एक expression हो सकती है। यही technique हर बार manually गिनने की जगह लेती है।
dict और objects के साथ
user = {"name": "Asha", "marks": 91}
f"{user['name']} scored {user['marks']}" # f-string में सीधा access
"{name} scored {marks}".format(**user) # .format() में unpack
"%(name)s scored %(marks)s" % user # % operator में
# objects के साथ
class Student:
def __init__(self, name, marks):
self.name, self.marks = name, marks
def __repr__(self):
return f"Student({self.name!r}, {self.marks})"
s = Student("Asha", 91)
f"{s.name}" # Asha — attribute access
f"{s}" # Student('Asha', 91) — __repr__ चलता है
f"{s!s}" # str(s)
f"{s!r}" # repr(s) — logging में यही चाहिएLogging में हमेशा !r use करो। repr quotes और escapes दिखाता है, तो '' और 'Asha' का फर्क साफ दिखता है — खाली string वाला bug यहीं पकड़ा जाता है।
Date और time
from datetime import datetime, date
now = datetime(2026, 10, 11, 14, 30, 5)
f"{now:%Y-%m-%d}" # 2026-10-11
f"{now:%d/%m/%Y}" # 11/10/2026
f"{now:%H:%M:%S}" # 14:30:05
f"{now:%B %d, %Y}" # October 11, 2026
f"{now:%A}" # Sunday
f"{now:%Y-%m-%dT%H:%M:%S}" # ISO 8601
# .format() में भी वही
"{:%Y-%m-%d}".format(now)
now.strftime("%Y-%m-%d") # सीधा method — यही सबसे साफ है
आम गलतियाँ
fprefix भूल जाना।"{name} scored"बिनाfके literal text है — braces ज्यों की त्यों print होंगे। सबसे आम गलती।%में tuple न देना। एक ही value हो तो भी(value,)लिखना पड़ता है;% valueअलग व्यवहार करता है।.format()में named और positional मिलाना। एक बार named use किया तो सब named होने चाहिए।- f-string में वही quote दोबारा। Python 3.11 तक
f"{d["key"]}"SyntaxErrorहै — अंदर single quote use करो। 3.12+ में ठीक है। - Logging में f-string use करना।
logger.debug(f"x={x}")हमेशा string बनाता है, भले level off हो।logger.debug("x=%s", x)लिखो।
name = "Asha"
print("{name} scored") # {name} scored — f नहीं लगाया!
print(f"{name} scored") # Asha scored
# logging वाली गलती
logger.debug(f"processing {len(huge_list)} items") # हमेशा बनता है
logger.debug("processing %d items", len(huge_list)) # सही — lazy
कौन सा चुनें
नया code: हमेशा f-string। पढ़ने में आसान, सबसे तेज़, और expression सीधे लिख सकते हो। .format() तब जब template string अलग जगह से आ रहा हो — जैसे config file, message catalog, या user-facing template। % operator सिर्फ पुराने code को पढ़ते वक्त पहचानने के लिए; नया मत लिखो, और logging में %-style lazy formatting ही सही है।
# f-string — नया code
f"{user.name} scored {score:.1f}"
# .format() — template बाहर से आ रहा है
TEMPLATE = "{name} scored {marks:.1f}"
for u in users:
print(TEMPLATE.format(**u))
# logging — यही सही तरीका
logger.info("saved %d rows to %s", count, path)
🛠️ Practice करो (free, browser में)
पढ़ना काफी नहीं — यही bug खुद fix करके देखो। नीचे के problems browser में ही चलते हैं, कोई install नहीं, कोई login नहीं।
- Mixing text and numbers in print — str और int जोड़ने की गलती।
अक्सर पूछे जाने वाले सवाल
f-string क्या है?
Python 3.6 से आया string literal जिसमें f prefix लगता है। Braces के अंदर सीधे Python expression लिख सकते हो, और colon के बाद format spec जोड़ सकते हो जैसे {:.2f}। नया code हमेशा इसी से लिखना चाहिए।
f-string, .format() और % में कौन सा तेज़ है?
f-string सबसे तेज़ है, क्योंकि formatting compile के समय तय हो जाती है। पर असली फर्क readability का है। % operator सबसे पुराना है और नए code में नहीं लिखना चाहिए।
दो decimal तक कैसे दिखाएँ?
Colon के बाद .2f लगाओ — f"{value:.2f}"। ये round करता है, truncate नहीं। Width भी चाहिए तो f"{value:>10.2f}" से right-align कर सकते हो।
Percent कैसे दिखाएँ?
f"{0.915:.1%}" से 91.5% मिलता है — ये अपने आप 100 से गुणा करता है। अगर value पहले से 91.5 है तो f"{91.5:.0f}%" लिखो, वरना 9150% दिखेगा।
Logging में f-string क्यों नहीं?
क्योंकि f-string हमेशा string बनाता है, भले log level off हो और message फेंक दिया जाए। logger.debug("x=%s", x) लिखो — ये lazy है और सिर्फ तब format होता है जब message सचमुच log हो।