Python f-strings
In this page:
f"text {variable}"
f"text {expression:format_spec}"
f-strings का परिचय
f-string किसी string literal से पहले f या F लगाकर बनती है, जो Python को बताता है कि भीतर की हर {expression} को runtime पर evaluate करके उसका नतीजा सीधे text में जोड़ दे — f"Hello, {name}" बराबर के .format() call से छोटा भी है और साफ़ भी।
उदाहरण: Introduction to f-strings
name = "Alex"
print(f"Hello, {name}")
Expressions को Evaluate करना
क्योंकि f-string के braces में सिर्फ़ variable नाम नहीं, बल्कि जीवित Python expressions होती हैं, आप f"{a + b}" या f"{is_valid and count > 0}" लिख सकते हैं और Python नतीजा डालने से पहले उसी क्षण गणित या logic evaluate कर लेती है।
उदाहरण: Evaluating Expressions
a, b = 2, 3
print(f"{a + b}") # the expression a + b is evaluated inside the f-string
count = 5
print(f"{count > 0}") # a comparison is also a valid expression here
Floats को Format करना
braces के अंदर colon के बाद format spec जोड़ना, जैसे f"{price:.2f}", संख्या के दिखने को वैसे ही नियंत्रित करता है जैसे .format() करता है — rounding, padding और separators सब उसी mini-language से उपलब्ध हैं।
उदाहरण: Formatting Floats
price = 19.999
print(f"{price:.2f}")
Methods और Functions को Call करना
आप braces के भीतर सीधे functions और string methods बुला सकते हैं — f"{name.upper()}" — क्योंकि interpreter { और } के बीच जो भी expression हो उसे text में बदलने से पहले बस evaluate कर देता है।
उदाहरण: Calling Methods and Functions
name = "alex"
print(f"{name.upper()}")
Alignment और Debugging
debugging का शॉर्टहैंड f"{value=}" expression का source text और उसका वर्तमान value दोनों print करता है, जो अलग print("value:", value) line लिखे बिना troubleshooting के दौरान किसी variable की स्थिति जाँचने का तेज़ तरीका है।
उदाहरण: Alignments and Debugging
value = 42
print(f"{value=}")
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