Python में f-string से स्ट्रिंग फ़ॉर्मेटिंग
f-strings variables और expressions को सीधे text में डालते हैं, और colon के बाद format specifier decimals, width, alignment और separators को control करता है।
में f-string से स्ट्रिंग फ़ॉर्मेटिंग क्या है?
f-strings variables और expressions को सीधे text में डालते हैं, और colon के बाद format specifier decimals, width, alignment और separators को control करता है।
Python f-strings और format specifiers से readable output बनाएं।
इसका उपयोग कब करें?
- चलने योग्य code से Python syntax सीखें।
- बड़ी programming समस्याओं से पहले मजबूत आधार बनाएँ।
- स्थानीय setup के बिना किसी विचार को तुरंत जाँचें।
उदाहरण कोड
name = "Lin"
score = 92.456
items = 3
# f-strings put expressions inside {} directly in the text.
print(f"{name} scored {score} points")
# Format specifiers after a colon control how values look.
print(f"Rounded: {score:.1f}")
print(f"Price: ${19.5:.2f}")
print(f"Padded: [{items:>5}] [{items:<5}] [{items:^5}]")
print(f"Thousands: {1234567:,}")
print(f"Percent: {0.875:.0%}")
# Any expression works, including calls and arithmetic.
print(f"{name.upper()} has {items * 2} tickets")
# A table with aligned columns.
for product, price in [("Tea", 2.5), ("Coffee", 3.75)]:
print(f"{product:<8}{price:>6.2f}")
अपेक्षित आउटपुट
Lin scored 92.456 points
Rounded: 92.5
Price: $19.50
Padded: [ 3] [3 ] [ 3 ]
Thousands: 1,234,567
Percent: 88%
LIN has 6 tickets
Tea 2.50
Coffee 3.75
यह कैसे काम करता है
.1f एक decimal तक round करता है, e5 और c5 पाँच characters के अंदर align करते हैं, , thousands separators जोड़ता है और .0% fraction को percentage के रूप में दिखाता है।
मान बदलें और Python इंस्टॉल किए बिना CodeUtility ऑनलाइन Python कंपाइलर में प्रोग्राम चलाएँ।
अभ्यास के कार्य
बड़े dataset पर जाने से पहले input बदलें और edge cases की जाँच करें।
- Code चलाने से पहले output का अनुमान लगाएँ।
- खाली और गलत input संभालें।
- Logic को function में रखें और tests जोड़ें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
- Multiplication Table Row List the first multiples of a number. आसान
- Count Uppercase Letters Count the capital letters in a text. आसान
- Initials From a Name Build uppercase initials from a full name. आसान