Python Format Strings
In this page:
"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
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
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
price = 19.999
print("{:.2f}".format(price))
Alignment और Padding
Field-width और alignment specifiers आपको values को निश्चित चौड़ाई तक pad करने देते हैं, और बाएँ के लिए <, दाएँ के लिए > या केंद्र के लिए ^ चुनने देते हैं — console output में संख्याओं या text के columns को सीध में लाने की मानक तकनीक।
उदाहरण: Alignment and Padding
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
print("{0} {1} {0}".format("echo", "middle"))
Chapter Quiz — Complete all 16 topics to unlock
0/16 topics done
Complete these topics first:
- Python print()
- Python input()
- Python Format Strings
- Python f-strings
- Python String Formatting
- Python Arithmetic Operators
- Python Relational Operators
- Python Logical Operators
- Python Bitwise Operators
- Python Assignment Operators
- Python Increment & Decrement
- Python Ternary Operator
- Python Operator Precedence
- Python Identity Operators
- Python Membership Operators
- Python Operators