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

Python f-strings

एक f-string एक ऐसा वाक्य है जिसमें छोटी-छोटी खिड़कियाँ होती हैं जहाँ से आपकी values दिखती हैं। आप curly braces के अंदर variable का नाम लिखते हैं और Python वहीं उसकी value रख देता है।
Syntax
python
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

python
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

python
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

python
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

python
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

python
value = 42
print(f"{value=}")
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.