← Back to Python Course | Chapter 2: Input, Output & Operators | Lesson 3 of 16

Python Format Strings

format() method एक खाली-जगह-भरो वाले वाक्य जैसा है: आप खाली स्लॉट्स के साथ वाक्य लिखते हैं और फिर उन्हें भरने के लिए शब्द देते हैं। यह बदलती हुई values के साथ संदेश बनाने में मदद करता है।
Syntax
python
"text {} and {}".format(value1, value2)
"text {name}".format(name=value)

बुनियादी .format() Method

.format() method string के {} placeholders को उन arguments से बदल देता है जो आप देते हैं, उसी क्रम में जिसमें वे आते हैं — "{} is {}".format(name, age) — जिससे आप + से टुकड़े जोड़े बिना पठनीय strings बना सकते हैं।

उदाहरण: Basic .format() Method

python
name = "Alex"
age = 30
print("{} is {}".format(name, age))  # {} placeholders filled in order

Named Placeholders

placeholders को positional छोड़ने के बजाय नाम देना, जैसे "{name} is {age}".format(name=name, age=age), template को खुद-समझाने वाला बनाता है और arguments के गलत क्रम में पास होने से होने वाले bugs से बचाता है।

उदाहरण: Named Placeholders

python
name = "Alex"
age = 30
print("{name} is {age}".format(name=name, age=age))  # named placeholders, order-independent

Decimals को Format करना

braces के अंदर colon और format spec जोड़ना, जैसे {:.2f}, संख्या के दिखने का तरीका नियंत्रित करता है — इस मामले में float को ठीक दो दशमलव स्थानों तक round करना, जो मुद्रा या प्रतिशत से जुड़ी किसी भी चीज़ के लिए ज़रूरी है।

उदाहरण: Formatting Decimals

python
price = 19.999
print("{:.2f}".format(price))

Alignment और Padding

Field-width और alignment specifiers आपको values को निश्चित चौड़ाई तक pad करने देते हैं, और बाएँ के लिए <, दाएँ के लिए > या केंद्र के लिए ^ चुनने देते हैं — console output में संख्याओं या text के columns को सीध में लाने की मानक तकनीक।

उदाहरण: Alignment and Padding

python
print("{:<10}|".format("left"))  # < left-aligns within a width of 10
print("{:>10}|".format("right"))  # > right-aligns within a width of 10
print("{:^10}|".format("mid"))  # ^ centers within a width of 10

Arguments का दोबारा उपयोग

braces के अंदर index संख्याएँ रखना, जैसे "{0} {1} {0}", एक ही argument को कई बार इस्तेमाल करने या उसे pass किए गए क्रम से अलग क्रम में दिखाने देता है, function call में value को दोहराए बिना।

उदाहरण: Reusing Arguments

python
print("{0} {1} {0}".format("echo", "middle"))
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.