Python String Formatting: % formatting, format() method, f-strings Notes in Hindi & English : स्ट्रिंग फॉर्मेटिंग: आधुनिक f-strings (f'{var}') और format() और 20 महत्वपूर्ण MCQ प्रश्न (Rajasthan IT Exam)

Post a Comment

PGDCA, BCA, B-Tech, MCA, M-Tech, B.Sc computer science राजस्थान सूचना सहायक व कंप्यूटर शिक्षक विशेष नोट्स: इस अध्याय में हम Python String Formatting: % formatting, format() method, f-strings (स्ट्रिंग फॉर्मेटिंग: आधुनिक f-strings (f'{var}') और format()) की संपूर्ण थ्योरी, मुख्य तकनीकी बिंदु, तुलनात्मक तालिका और विगत परीक्षाओं के पैटर्न पर आधारित 20 अति-महत्वपूर्ण बहुविकल्पीय प्रश्न (MCQs) विस्तृत हिंदी व अंग्रेजी व्याख्या सहित पढ़ेंगे।

Overview: Python supports three string formatting mechanisms: legacy printf-style (%) formatting, the flexible str.format() method, and modern f-strings (formatted string literals introduced in Python 3.6). f-strings evaluate embedded Python expressions inline at runtime, run faster than % and format(), and share the format specification mini-language (alignment, width, precision, thousands separators, and = debugging).

अध्याय सार: पायथन स्ट्रिंग फॉर्मेटिंग के तीन तरीके प्रदान करता है: पारंपरिक % फॉर्मेटिंग, str.format() मेथड और आधुनिक f-strings (पायथन 3.6 से)। f-strings रनटाइम पर सीधे पायथन एक्सप्रेशन को हल करती हैं, सबसे तेज काम करती हैं, तथा अलाइनमेंट, दशमलव सटीकता, हजार विभाजक और = डिबगिंग जैसे फॉर्मेट स्पेसिफिकेशन का समर्थन करती हैं।

Python String Formatting: % formatting, format() method, f-strings: Detailed Notes & Architecture (स्ट्रिंग फॉर्मेटिंग: आधुनिक f-strings (f'{var}') और format())

1. Legacy % Formatting (printf-Style Specifiers) (पारंपरिक % फॉर्मेटिंग (printf-शैली))

[EN] Python's oldest formatting syntax borrows C's printf specifiers—such as %s (str), %d (int), %f / %.2f (float), %x (hex), and %% (literal percent sign)—applied via the modulo operator. Multiple placeholders take a tuple ('%s is %d' % (name, age)) or dict mapping ('%(k)s' % {'k': 1}). A notorious pitfall occurs when formatting a single tuple value: '%s' % ((1, 2),) works, whereas '%s' % (1, 2) raises TypeError: not all arguments converted during string formatting, which is why modern code avoids %.

[HI] पायथन की सबसे पुरानी फॉर्मेटिंग C भाषा के %s (स्ट्रिंग), %d (पूर्णांक), %f/%.2f (फ्लोट), %x (हेक्स) और %% (शाब्दिक %) स्पेसिफायर्स का उपयोग करती है। एक से अधिक मान देने के लिए टपल या डिक्शनरी का उपयोग होता है। इसमें एक बड़ी समस्या तब आती है जब एक ही टपल को प्रिंट करना हो: '%s' % (1, 2) लिखने पर TypeError आता है जब तक उसे ((1, 2),) में न लपेटा जाए; इसी कारण आधुनिक कोड में % से बचा जाता है।

2. The str.format() Method and Positional/Keyword Fields (str.format() मेथड और पोजिशनल/कीवर्ड फील्ड्स)

[EN] Introduced in Python 2.6/3.0, str.format() replaces {} placeholders using sequential ('{} {}'.format('A', 'B')), indexed ('{1} {0}'.format('A', 'B')), or keyword ('{user}'.format(user='Raj')) arguments, and even supports indexing/attributes ('{0[1]}'). Literal curly braces are escaped by doubling them as {{ and }}. Though cleaner than %, format() requires repeating variable names or argument indices and builds a function call, making it slightly slower and more verbose than f-strings.

[HI] पायथन 2.6/3.0 में आया str.format() मेथड {} प्लेसहोल्डर्स को क्रमिक, इंडेक्स ({1} {0}) या कीवर्ड ({user}) आर्ग्युमेंट्स से भरता है और ऑब्जेक्ट इंडेक्सिंग ({0[1]}) भी सपोर्ट करता है। आउटपुट में वास्तविक कर्ली ब्रैकेट दिखाने के लिए उन्हें {{ और }} के रूप में दोगुना लिखा जाता है। यह % से बेहतर है, लेकिन वेरिएबल नाम दोहराने पड़ने के कारण f-strings की तुलना में थोड़ा लंबा और धीमा होता है।

3. Modern f-Strings (Python 3.6+, = Debug Specifier, PEP 701) (आधुनिक f-Strings (पायथन 3.6+, = डिबग और PEP 701))

[EN] Prefixed with f or F (e.g., f'{name} scored {marks + 5:.1f}'), f-strings evaluate arbitrary Python expressions inside { } at runtime and compile directly into fast bytecode without a .format() call. Python 3.8 added the self-documenting debug specifier '=': writing f'{x=}' prints 'x=10', and f'{a + b = }' prints 'a + b = 30'. Python 3.12 (PEP 701) removed earlier parser limits so f-strings can reuse identical quotes inside expressions, include comments, span lines, and contain backslashes inside {...}.

[HI] f या F प्रीफिक्स वाली f-strings (जैसे f'{name} scored {marks + 5:.1f}') रनटाइम पर सीधे कोष्ठक के अंदर पायथन एक्सप्रेशन को हल करती हैं और बिना मेथड कॉल के तेज बाइटकोड बनाती हैं। पायथन 3.8 में सेल्फ-डॉक्यूमेंटिंग '=' स्पेसिफायर जोड़ा गया: f'{x=}' सीधे 'x=10' प्रिंट करता है। पायथन 3.12 (PEP 701) ने पुराने प्रतिबंध हटा दिए जिससे अब f-string के {...} के भीतर समान कोट्स, टिप्पणियाँ और बैकस्लैश भी लिखे जा सकते हैं।

4. Format Specification Mini-Language and Conversions (!r, !s, !a) (फॉर्मेट स्पेसिफिकेशन मिनी-लैंग्वेज और रूपांतरण (!r, !s, !a))

[EN] Both .format() and f-strings share the mini-language grammar [[fill]align][sign][#][0][width][grouping][.precision][type] after a colon ':'. Alignment flags are < (left), > (right), ^ (center), and = (sign-aware numeric padding), e.g., f'{42:05d}' -> '00042' and f'{"HI":*^6}' -> '**HI**'. Useful type/grouping options include ',' or '_' for thousands (f'{1000000:,}' -> '1,000,000'), '%' for percentage (0.25:.1% -> '25.0%'), b/o/x/X for bases, and conversion flags !s (str), !r (repr), !a (ascii) before the colon.

[HI] .format() और f-strings दोनों कोलन ':' के बाद एक ही मिनी-लैंग्वेज का उपयोग करते हैं। अलाइनमेंट फ्लैग्स में < (बाएँ), > (दाएँ), ^ (मध्य) और = शामिल हैं, जैसे f'{42:05d}' -> '00042' और f'{"HI":*^6}' -> '**HI**'। अन्य उपयोगी विकल्प: हजार विभाजक (',' या '_'), प्रतिशत ('%'), आधार (b बाइनरी, o ऑक्टल, x हेक्स), तथा कोलन से पहले लगने वाले !s (str), !r (repr) और !a (ascii) कन्वर्जन फ्लैग्स।

Syntax, Formula & Technical Example (Python String Formatting: % formatting, format() method, f-strings)

name, score = 'Asha', 87.456
print('Hi %s: %.1f' % (name, score))          # Hi Asha: 87.5
print('{1} -> {0:>6.2f}'.format(score, name)) # Asha ->  87.46
print(f'{name!r} scored {score:.2f}')         # 'Asha' scored 87.46
n = 1234567
print(f'{n:,} | {10:04b} | {0.75:.0%}')       # 1,234,567 | 1010 | 75%
x = 5
print(f'{x * 2=}')                            # x * 2=10

Python String Formatting: % formatting, format() method, f-strings Quick Reference & Comparison Table

Formatting StyleSyntax ExampleKey Exam Fact
% formatting'%s: %.2f' % ('Pi', 3.1415)Tuple pitfall; %% prints literal %
str.format()'{1} {0:.1f}'.format(9.56, 'A')Escape literal braces as {{ and }}
f-string (3.6+)f'{name!r} = {val:,}'Fastest; evaluates expressions inline
Debug = (3.8+)f'{x + 1=}'Outputs both expression text and value

Python String Formatting: % formatting, format() method, f-strings Top 20 Bilingual MCQs with Answers

Q1. In which Python version were f-strings (PEP 498) introduced?

(f-strings (PEP 498) को किस पायथन संस्करण में पेश किया गया था?)

(A) Python 3.6

(B) Python 3.4

(C) Python 3.0

(D) Python 3.8

Correct Answer: (A)

[EN] PEP 498 added formatted string literals (f-strings) in Python 3.6; Python 3.8 later added the '=' debug specifier.

[HI] PEP 498 के तहत f-strings को पायथन 3.6 में जोड़ा गया था; बाद में 3.8 में '=' डिबग फीचर आया।

Q2. What is the output of: x = 7; print(f'{x + 3=}')?

(x = 7; print(f'{x + 3=}') का आउटपुट क्या होगा?)

(A) 10

(B) x + 3=10

(C) SyntaxError

(D) x + 3 = 10

Correct Answer: (B)

[EN] The '=' specifier in f-strings (Python 3.8+) prints the exact expression text followed by '=' and its repr/formatted result (preserving spaces).

[HI] पायथन 3.8+ में f'{x + 3=}' बिना स्पेस बदले सटीक एक्सप्रेशन और '=' के साथ उसका मान x + 3=10 प्रिंट करता है।

Q3. What does '{:*^7}'.format('PY') produce?

('{:*^7}'.format('PY') क्या परिणाम देता है?)

(A) '**PY***'

(B) '*****PY'

(C) 'PY*****'

(D) '***PY**'

Correct Answer: (A)

[EN] Fill='*', align='^' (center), width=7 on length-2 'PY' needs 5 padding chars: Python places 2 on the left and 3 on the right.

[HI] चौड़ाई 7 में 2 अक्षर के 'PY' को '*' से केंद्र में (^) रखने पर बाईं ओर 2 और दाईं ओर 3 तारे जुड़कर '**PY***' बनता है।

Q4. How do you print literal curly braces {10} using an f-string when x = 10?

(जब x = 10 हो, तो f-string द्वारा आउटपुट में {10} प्रिंट करने का सही सिंटैक्स क्या है?)

(A) f'{{{x}}}'

(B) f'\{{x}\}'

(C) f'{{x}}'

(D) f'{x}'

Correct Answer: (A)

[EN] Doubling braces {{ and }} escapes literal braces, while the innermost {x} evaluates x, producing '{10}'.

[HI] कर्ली ब्रैकेट को एस्केप करने के लिए {{ और }} लिखते हैं तथा अंदर {x} से मान मिलता है, अतः f'{{{x}}}' से {10} आता है।

Q5. What is the output of: print(f'{0.256:.1%}')?

(print(f'{0.256:.1%}') का आउटपुट क्या होगा?)

(A) 25%

(B) 25.6%

(C) 25.60%

(D) 0.3%

Correct Answer: (B)

[EN] The '%' format type multiplies the number by 100 and displays it with 1 decimal place (fixed) plus a '%' sign.

[HI] '%' फॉर्मेट प्रकार संख्या को 100 से गुणा करके .1 सटीकता के साथ प्रतिशत चिह्न (%) जोड़ता है।

Q6. What happens when you execute 'Tuple: %s' % (1, 2)?

('Tuple: %s' % (1, 2) चलाने पर क्या होता है?)

(A) Prints 'Tuple: 1'

(B) Prints 'Tuple: (1, 2)'

(C) Raises ValueError

(D) Raises TypeError

Correct Answer: (D)

[EN] The % operator unpacks (1, 2) as two arguments for one %s placeholder, raising TypeError; pass ((1, 2),) instead.

[HI] % ऑपरेटर (1, 2) को एक टपल मानने के बजाय दो अलग आर्ग्युमेंट समझ लेता है और TypeError देता है।

Q7. What is the output of: s = 'hi'; print(f'{s!r}')?

(s = 'hi'; print(f'{s!r}') का आउटपुट क्या होगा?)

(A) hi

(B) 'hi'

(C) r'hi'

(D) SyntaxError

Correct Answer: (B)

[EN] The !r conversion flag invokes repr(s) before formatting, adding quotes around the string.

[HI] !r कन्वर्जन फ्लैग फॉर्मेट करने से पहले repr(s) चलाता है, जिससे कोट्स सहित 'hi' आउटपुट आता है।

Q8. What does f'{12:06b}' produce?

(f'{12:06b}' का परिणाम क्या होता है?)

(A) '1100'

(B) '0b1100'

(C) ' 1100'

(D) '001100'

Correct Answer: (D)

[EN] b formats 12 in binary ('1100') and 06 pads with leading zeros to a total width of 6.

[HI] b से 12 का बाइनरी '1100' बनता है और 06 कुल चौड़ाई 6 पूरी करने के लिए आगे दो शून्य लगाता है -> '001100'।

Q9. What is the output of: print('{1} + {0}'.format(5, 10))?

(print('{1} + {0}'.format(5, 10)) का आउटपुट क्या होगा?)

(A) IndexError

(B) 5 + 10

(C) 15

(D) 10 + 5

Correct Answer: (D)

[EN] Index 1 refers to the second argument (10) and index 0 refers to the first argument (5).

[HI] इंडेक्स 1 दूसरे आर्ग्युमेंट (10) और इंडेक्स 0 पहले आर्ग्युमेंट (5) को दर्शाता है, अतः 10 + 5 प्रिंट होगा।

Q10. How do you format a literal percent sign using old-style % formatting in '100% done'?

(पुरानी % फॉर्मेटिंग से '50% pass' जैसा प्रतिशत चिह्न प्रिंट करने के लिए क्या लिखते हैं?)

(A) '%d{{%}} pass' % 50

(B) '%d%% pass' % 50

(C) '%d\% pass' % 50

(D) '%d% pass' % 50

Correct Answer: (B)

[EN] In printf-style formatting, %% escapes a literal percent character.

[HI] % फॉर्मेटिंग में शाब्दिक प्रतिशत (%) प्रिंट करने के लिए %% लिखा जाता है।

Q11. What does f'{1000000:_}' output?

(f'{1000000:_}' का आउटपुट क्या होता है?)

(A) '1,000,000'

(B) '___1000000'

(C) ValueError

(D) '1_000_000'

Correct Answer: (D)

[EN] Both ',' and '_' act as thousands-grouping separators in Python 3.6+ format specifications.

[HI] पायथन 3.6+ के फॉर्मेट स्पेसिफिकेशन में ',' और '_' दोनों हजार विभाजक के रूप में काम करते हैं।

Q12. Which formatting approach is generally fastest at runtime in CPython?

(CPython में रनटाइम पर कौन सी स्ट्रिंग फॉर्मेटिंग विधि सामान्यतः सबसे तेज होती है?)

(A) % formatting

(B) f-strings

(C) str.format()

(D) string.Template

Correct Answer: (B)

[EN] f-strings compile directly into dedicated bytecode instructions without dictionary/method dispatch overhead.

[HI] f-strings बिना मेथड कॉल या अतिरिक्त पार्सिंग ओवरहेड के सीधे तेज बाइटकोड में संकलित होती हैं।

Q13. What is the output of: data = {'k': 9}; print('{k}'.format(**data))?

(data = {'k': 9}; print('{k}'.format(**data)) का आउटपुट क्या होगा?)

(A) 9

(B) {'k': 9}

(C) k

(D) KeyError

Correct Answer: (A)

[EN] Unpacking **data passes k=9 as a keyword argument to format(), filling {k} with 9.

[HI] **data डिक्शनरी को कीवर्ड आर्ग्युमेंट k=9 के रूप में format() को पास करता है जिससे {k} का मान 9 आता है।

Q14. Which Python release (PEP 701) lifted restrictions so f-strings can reuse quotes and include backslashes inside {...}?

(किस पायथन संस्करण (PEP 701) ने f-strings के {...} के भीतर समान कोट्स और बैकस्लैश लिखने की अनुमति दी?)

(A) Python 3.12

(B) Python 3.8

(C) Python 3.10

(D) Python 3.6

Correct Answer: (A)

[EN] PEP 701 in Python 3.12 formalized f-string tokenization, allowing nested identical quotes, multiline comments, and backslashes inside expressions.

[HI] पायथन 3.12 (PEP 701) ने f-string के एक्सप्रेशन में समान कोट्स, टिप्पणियाँ और बैकस्लैश लिखने के पुराने प्रतिबंध हटा दिए।

Q15. What is the output of: print(f'{3.14159:.2f}' if True else 'no')?

(print(f'{3.14159:.2f}' if True else 'no') का आउटपुट क्या होगा?)

(A) 3.14159

(B) TypeError

(C) 3.15

(D) 3.14

Correct Answer: (D)

[EN] The precision specifier .2f rounds 3.14159 to two decimal digits: '3.14'.

[HI] .2f फॉर्मेट स्पेसिफायर 3.14159 को दशमलव के दो स्थानों तक राउंड करके '3.14' प्रिंट करता है।

Q16. Which of the following statements about Python string formatting is NOT true?

(पायथन स्ट्रिंग फॉर्मेटिंग के बारे में निम्नलिखित में से कौन सा कथन सत्य नहीं है?)

(A) f-strings evaluate embedded expressions only once at import time and cache them forever

(B) Conversion flags !s, !r, and !a appear before the colon in replacement fields

(C) Leaving placeholders empty '{}' in str.format() uses arguments sequentially

(D) Both str.format() and f-strings support the format specification mini-language

Correct Answer: (A)

[EN] f-strings evaluate their embedded expressions dynamically at runtime every time the f-string statement executes (which is why they cannot serve as static docstrings).

[HI] f-strings इम्पोर्ट टाइम पर नहीं बल्कि हर बार कोड निष्पादित होने पर रनटाइम पर अपने एक्सप्रेशन का मूल्यांकन करती हैं।

Q17. Within Python String Formatting: % formatting, format() method, f-strings, which formatting style directly maps to: "'%s: %.2f' % ('Pi', 3.1415)"?

(Python String Formatting: % formatting, format() method, f-strings में कौन सा Formatting Style सीधे "'%s: %.2f' % ('Pi', 3.1415)" से संबंधित है?)

(A) Debug = (3.8+)

(B) f-string (3.6+)

(C) % formatting

(D) str.format()

Correct Answer: (C)

[EN] In Python String Formatting: % formatting, format() method, f-strings, '% formatting' handles ''%s: %.2f' % ('Pi', 3.1415)' (Tuple pitfall; %% prints literal %).

[HI] Python String Formatting: % formatting, format() method, f-strings में '% formatting' का कार्य/विवरण ''%s: %.2f' % ('Pi', 3.1415)' (Tuple pitfall; %% prints literal %) है।

Q18. Which option accurately describes 'str.format()' in Python String Formatting: % formatting, format() method, f-strings?

(Python String Formatting: % formatting, format() method, f-strings के संदर्भ में 'str.format()' की सही विशेषता कौन सी है?)

(A) '{1} {0:.1f}'.format(9.56, 'A')

(B) f'{x + 1=}'

(C) '%s: %.2f' % ('Pi', 3.1415)

(D) f'{name!r} = {val:,}'

Correct Answer: (A)

[EN] 'str.format()' provides ''{1} {0:.1f}'.format(9.56, 'A')' — key point: Escape literal braces as {{ and }}.

[HI] 'str.format()' का मुख्य विवरण ''{1} {0:.1f}'.format(9.56, 'A')' है (Escape literal braces as {{ and }})।

Q19. In Python String Formatting: % formatting, format() method, f-strings, identify the correct parameter for the specification: "f'{name!r} = {val:,}'".

(Python String Formatting: % formatting, format() method, f-strings में "f'{name!r} = {val:,}'" विवरण किस विकल्प के लिए सही है?)

(A) Debug = (3.8+)

(B) f-string (3.6+)

(C) str.format()

(D) % formatting

Correct Answer: (B)

[EN] 'f-string (3.6+)' corresponds to 'f'{name!r} = {val:,}'' (Fastest; evaluates expressions inline).

[HI] 'f-string (3.6+)' का संबंध 'f'{name!r} = {val:,}'' (Fastest; evaluates expressions inline) से है।

Q20. Considering Python String Formatting: % formatting, format() method, f-strings, what key behavior defines 'Debug = (3.8+)'?

(Python String Formatting: % formatting, format() method, f-strings में 'Debug = (3.8+)' की मुख्य भूमिका या मान क्या है?)

(A) '{1} {0:.1f}'.format(9.56, 'A')

(B) '%s: %.2f' % ('Pi', 3.1415)

(C) f'{name!r} = {val:,}'

(D) f'{x + 1=}'

Correct Answer: (D)

[EN] 'Debug = (3.8+)' represents 'f'{x + 1=}'' (Outputs both expression text and value).

[HI] 'Debug = (3.8+)' का अर्थ/मान 'f'{x + 1=}'' है (Outputs both expression text and value)।

Python String Formatting: % formatting, format() method, f-strings — Exam FAQs

Q1: When should I still use str.format() instead of an f-string?

f-strings के बावजूद मुझे str.format() का उपयोग कब करना चाहिए?

[EN] Use str.format() (or string.Template) when the template string is loaded from an external file, database, translation catalog, or user input, because f-strings must be literal expressions evaluated immediately in code.

[HI] जब टेम्पलेट स्ट्रिंग किसी बाहरी फाइल, डेटाबेस या अनुवाद फाइल से आती हो और मान बाद में भरने हों, तब str.format() का उपयोग करें, क्योंकि f-strings तुरंत कोड में मूल्यांकित होती हैं।

Q2: Why can't an f-string be used as a function docstring?

किसी फंक्शन की डॉकस्ट्रिंग के रूप में f-string का उपयोग क्यों नहीं हो पाता?

[EN] Because f-strings are runtime-evaluated expressions rather than compile-time constant string literals, Python does not treat them as __doc__ (leaving __doc__ as None).

[HI] क्योंकि f-strings रनटाइम पर हल होने वाले एक्सप्रेशन हैं न कि स्थिर स्ट्रिंग लिटरल; अतः पायथन उन्हें __doc__ में नहीं सहेजता।

Q3: What does the '=' alignment specifier do in Python format strings?

फॉर्मेट स्ट्रिंग में '=' अलाइनमेंट स्पेसिफायर क्या करता है?

[EN] When padding numbers like f'{-42:=6d}', '=' places padding between the sign and the digits ('- 42'), unlike '>' which yields ' -42'.

[HI] संख्याओं की पैडिंग करते समय '=' चिह्न (- या +) और अंकों के बीच स्पेस/पैडिंग भरता है, जैसे f'{-42:=05d}' से '-0042' बनता है।

Related Posts

  • Loading related posts...

Post a Comment

Search Topic Notes & 20 MCQs (Hindi / English)