पायथन स्ट्रिंग प्रारूप ()

स्ट्रिंग प्रारूप () विधि दी गई स्ट्रिंग को पायथन में एक अच्छे आउटपुट में बदल देती है।

format()विधि का सिंटैक्स है:

 template.format (p0, p1,…, k0 = v0, k1 = v1,…)

यहाँ, p0, p1,… स्थितियुक्त तर्क हैं और, k0, k1,… क्रमशः मान v0, v1,… के साथ खोजशब्द तर्क हैं।

और, तर्कों के लिए प्लेसहोल्डर के साथ प्रारूप कोड का मिश्रण है।

स्ट्रिंग प्रारूप () पैरामीटर

format()विधि किसी भी संख्या में पैरामीटर लेती है। लेकिन, दो प्रकार के मापदंडों में विभाजित है:

  • स्थितिगत पैरामीटर - उन मापदंडों की सूची जो घुंघराले ब्रेसिज़ के अंदर पैरामीटर के सूचकांक के साथ पहुँचा जा सकता है(index)
  • कीवर्ड पैरामीटर - प्रकार कुंजी के मानों की सूची = मान, जो घुंघराले ब्रेसिज़ के अंदर पैरामीटर की कुंजी के साथ पहुँचा जा सकता है(key)

स्ट्रिंग प्रारूप से वापसी मूल्य ()

format()विधि स्वरूपित स्ट्रिंग देता है।

स्ट्रिंग प्रारूप () कैसे काम करता है?

format()यह करने के लिए पारित कर दिया तर्क का प्रकार पढ़ता है और स्ट्रिंग में परिभाषित प्रारूप कोड के अनुसार यह प्रारूप।

स्थिति संबंधी तर्कों के लिए

स्थिति संबंधी तर्क

यहाँ, Argument 0 एक स्ट्रिंग है "Adam" और Argument 1 एक फ्लोटिंग नंबर 230.2346 है।

नोट: तर्क सूची पायथन में 0 से शुरू होती है।

स्ट्रिंग "Hello (0), your balance is (1:9.3f)"टेम्पलेट स्ट्रिंग है। इसमें स्वरूपण के लिए प्रारूप कोड हैं।

घुंघराले ब्रेसिज़ बस तर्कों के लिए रखे जाते हैं। उपरोक्त उदाहरण में, (0) "एडम" के लिए प्लेसहोल्डर है और (1: 9.3f) 230.2346 के लिए प्लेसहोल्डर है।

टेम्पलेट स्ट्रिंग का संदर्भ के बाद से format()के रूप में तर्क (0)और (1), तर्क स्थितीय तर्क हैं। इन दोनों को संख्याओं के बिना भी संदर्भित किया जा सकता है ()और पायथन आंतरिक रूप से संख्याओं में परिवर्तित करता है।

आंतरिक रूप से,

  • चूंकि "एडम" 0 वें तर्क है, इसे इसके स्थान पर रखा गया है (0)। चूंकि, (0)इसमें कोई अन्य प्रारूप कोड नहीं है, इसलिए यह कोई अन्य संचालन नहीं करता है।
  • हालांकि, यह 1 सेंट तर्क 230.2346 के लिए मामला नहीं है । यहां, (1:9.3f)230.2346 को इसके स्थान पर रखा गया है और ऑपरेशन 9.3f करता है।
  • एफ निर्दिष्ट करता है कि प्रारूप एक फ्लोट संख्या के साथ काम कर रहा है। यदि सही ढंग से निर्दिष्ट नहीं है, तो यह एक त्रुटि देगा।
  • "" से पहले का हिस्सा। (9) न्यूनतम चौड़ाई निर्दिष्ट करता है / संख्या (२३०.२३४६) को पैडिंग कर सकता है। इस स्थिति में, 230.2346 को "" सहित न्यूनतम 9 स्थानों को आवंटित किया गया है।
    यदि कोई संरेखण विकल्प निर्दिष्ट नहीं है, तो यह शेष रिक्त स्थान के दाईं ओर संरेखित है। (स्ट्रिंग्स के लिए, इसे बाईं ओर संरेखित किया गया है।)
  • "के बाद का हिस्सा।" (३) दी गई संख्या तक दशमलव भाग (२३४६) को काट देता है। इस मामले में, 3 स्थानों के बाद 2346 को काट दिया जाता है।
    शेष संख्या (46) 235 के आउटपुट से गोल है।

कीवर्ड तर्क के लिए

कीवर्ड तर्क

हमने कीवर्ड और स्थिति संबंधी तर्कों के बीच अंतर दिखाने के लिए ऊपर से एक ही उदाहरण का उपयोग किया है।

यहां, केवल मापदंडों के बजाय, हमने मापदंडों के लिए एक कुंजी-मूल्य का उपयोग किया है। अर्थात्, नाम = "एडम" और blc = 230.2346।

चूँकि इन मापदंडों को उनकी चाबियाँ (नाम) और (blc: 9.3f) के रूप में संदर्भित किया जाता है, उन्हें कीवर्ड या नाम तर्क के रूप में जाना जाता है।

आंतरिक रूप से,

  • प्लेसहोल्डर (नाम) को नाम के मूल्य से बदल दिया जाता है - "एडम"। चूंकि इसमें कोई अन्य प्रारूप कोड नहीं है, इसलिए "एडम" रखा गया है।
  • तर्क blc = 230.2346 के लिए, प्लेसहोल्डर (blc: 9.3f) को 230.2346 मान से बदल दिया जाता है। लेकिन इसे बदलने से पहले, पिछले उदाहरण की तरह, यह इस पर 9.3f ऑपरेशन करता है।
    यह 230.235 आउटपुट करता है। दशमलव भाग को 3 स्थानों के बाद छोटा किया जाता है और शेष अंकों को गोल कर दिया जाता है। इसी तरह, कुल चौड़ाई 9 को दो रिक्त स्थान छोड़ते हुए असाइन किया गया है।

प्रारूप के साथ मूल स्वरूपण ()

format()विधि फ़ॉर्मेट करने के लिए सरल प्लेसहोल्डर के उपयोग की अनुमति देता है।

उदाहरण 1: डिफ़ॉल्ट, स्थिति और कीवर्ड तर्क के लिए मूल स्वरूपण

 # default arguments print("Hello (), your balance is ().".format("Adam", 230.2346)) # positional arguments print("Hello (0), your balance is (1).".format("Adam", 230.2346)) # keyword arguments print("Hello (name), your balance is (blc).".format(name="Adam", blc=230.2346)) # mixed arguments print("Hello (0), your balance is (blc).".format("Adam", blc=230.2346))

आउटपुट

नमस्ते एडम, आपका बैलेंस 230.2346 है। नमस्ते एडम, आपका बैलेंस 230.2346 है। नमस्ते एडम, आपका बैलेंस 230.2346 है। नमस्ते एडम, आपका बैलेंस 230.2346 है।

ध्यान दें: मिश्रित तर्कों के मामले में, कीवर्ड तर्कों को हमेशा स्थितीय तर्कों का पालन करना पड़ता है।

प्रारूप के साथ स्वरूपण संख्याएँ ()

आप नीचे दिए गए प्रारूप विनिर्देशक का उपयोग करके संख्याओं को प्रारूपित कर सकते हैं:

संख्या स्वरूपण प्रकार
प्रकार अर्थ
d दशमलव पूर्णांक
सी यूनिकोड चरित्र के अनुरूप
बी बाइनरी प्रारूप
अष्टक रूप
एक्स हेक्साडेसिमल प्रारूप (निचला मामला)
एक्स हेक्साडेसिमल प्रारूप (ऊपरी मामला)
एन 'घ' के समान। सिवाय यह संख्या विभाजक के लिए वर्तमान स्थानीय सेटिंग का उपयोग करता है
सँबोध वाचक चिन्ह। (लोअरकेस ई)
Exponential notation (uppercase E)
f Displays fixed point number (Default: 6)
F Same as 'f'. Except displays 'inf' as 'INF' and 'nan' as 'NAN'
g General format. Rounds number to p significant digits. (Default precision: 6)
G Same as 'g'. Except switches to 'E' if the number is large.
% Percentage. Multiples by 100 and puts % at the end.

Example 2: Simple number formatting

 # integer arguments print("The number is:(:d)".format(123)) # float arguments print("The float number is:(:f)".format(123.4567898)) # octal, binary and hexadecimal format print("bin: (0:b), oct: (0:o), hex: (0:x)".format(12))

Output

 The number is: 123 The number is:123.456790 bin: 1100, oct: 14, hex: c

Example 3: Number formatting with padding for int and floats

 # integer numbers with minimum width print("(:5d)".format(12)) # width doesn't work for numbers longer than padding print("(:2d)".format(1234)) # padding for float numbers print("(:8.3f)".format(12.2346)) # integer numbers with minimum width filled with zeros print("(:05d)".format(12)) # padding for float numbers filled with zeros print("(:08.3f)".format(12.2346))

Output

 1 2 1 2 3 4 1 2 . 2 3 5 0 0 0 1 2 0 0 1 2 . 2 3 5 

Here,

  • in the first statement, (:5d) takes an integer argument and assigns a minimum width of 5. Since, no alignment is specified, it is aligned to the right.
  • In the second statement, you can see the width (2) is less than the number (1234), so it doesn't take any space to the left but also doesn't truncate the number.
  • Unlike integers, floats has both integer and decimal parts. And, the mininum width defined to the number is for both parts as a whole including ".".
  • In the third statement, (:8.3f) truncates the decimal part into 3 places rounding off the last 2 digits. And, the number, now 12.235, takes a width of 8 as a whole leaving 2 places to the left.
  • If you want to fill the remaining places with zero, placing a zero before the format specifier does this. It works both for integers and floats: (:05d) and (:08.3f).

Example 4: Number formatting for signed numbers

 # show the + sign print("(:+f) (:+f)".format(12.23, -12.23)) # show the - sign only print("(:-f) (:-f)".format(12.23, -12.23)) # show space for + sign print("(: f) (: f)".format(12.23, -12.23))

Output

+12.230000 -12.230000 12.230000 -12.230000 1 2। 2 3 0 0 0 0 - 1 2। २ ३ ० ० ० ०

संरेखण के साथ संख्या स्वरूपण

संचालकों and =को संरेखण के लिए उपयोग किया जाता है जब संख्याओं के लिए एक निश्चित चौड़ाई निर्दिष्ट की जाती है।

संरेखण के साथ संख्या स्वरूपण
प्रकार अर्थ
< बचे हुए स्थान से संरेखित किया गया
^ शेष स्थान के लिए केंद्र संरेखित
> शेष स्थान के लिए ठीक संरेखित
= = हस्ताक्षरित (+) (-) को सबसे बाईं स्थिति में रखता है

उदाहरण 5: बाएं, दाएं और केंद्र संरेखण के साथ संख्या स्वरूपण

 # integer numbers with right alignment print("(:5d)".format(12)) # float numbers with center alignment print("(:^10.3f)".format(12.2346)) # integer left alignment filled with zeros print("(:<05d)".format(12)) # float numbers with center alignment print("(:=8.3f)".format(-12.2346))

आउटपुट

1 2 1 2। 2 3 5 1 2 0 0 0 - 1 2 २ ३ ५

नोट: पूर्णांक संख्याओं के लिए शून्य से भरा वाम संरेखण 3 उदाहरण के रूप में समस्याएं पैदा कर सकता है जो 12 के बजाय 12000 देता है।

स्ट्रिंग प्रारूपण के साथ ()

संख्या के रूप में, स्ट्रिंग को इसी तरह से स्वरूपित किया जा सकता है format()

Example 6: String formatting with padding and alignment

 # string padding with left alignment print("(:5)".format("cat")) # string padding with right alignment print("(:>5)".format("cat")) # string padding with center alignment print("(:^5)".format("cat")) # string padding with center alignment # and '*' padding character print("(:*^5)".format("cat"))

Output

 c a t c a t c a t * c a t * 

Example 7: Truncating strings with format()

 # truncating strings to 3 letters print("(:.3)".format("caterpillar")) # truncating strings to 3 letters # and padding print("(:5.3)".format("caterpillar")) # truncating strings to 3 letters, # padding and center alignment print("(:^5.3)".format("caterpillar"))

Output

 c a t c a t c a t 

Formatting class and dictionary members using format()

Python internally uses getattr() for class members in the form ".age". And, it uses __getitem__() lookup for dictionary members in the form "(index)".

Example 8: Formatting class members using format()

 # define Person class class Person: age = 23 name = "Adam" # format age print("(p.name)'s age is: (p.age)".format(p=Person()))

Output

 Adam's age is: 23 

Here, Person object is passed as a keyword argument p.

Inside the template string, Person's name and age are accessed using .name and .age respectively.

Example 9: Formatting dictionary members using format()

 # define Person dictionary person = ('age': 23, 'name': 'Adam') # format age print("(p(name))'s age is: (p(age))".format(p=person))

Output

 Adam's age is: 23 

Similar to class, person dictionary is passed as a keyword argument p.

Inside the template string, person's name and age are accessed using (name) and (age) respectively.

There's an easier way to format dictionaries in Python using str.format(**mapping).

 # define Person dictionary person = ('age': 23, 'name': 'Adam') # format age print("(name)'s age is: (age)".format(**person))

** is a format parameter (minimum field width).

Arguments as format codes using format()

You can also pass format codes like precision, alignment, fill character as positional or keyword arguments dynamically.

Example 10: Dynamic formatting using format()

 # dynamic string format template string = "(:(fill)(align)(width))" # passing format codes as arguments print(string.format('cat', fill='*', # dynamic float format template num = "(:(align)(width).(precision)f)" # passing format codes as arguments print(num.format(123.236,>

Output

 * * c a t * * 1 2 3 . 2 4 

Here,

  • In the first example, 'cat' is the positional argument is to be formatted. Likewise, fill='*', align='^' and width=5 are keyword arguments.
  • In the template string, these keyword arguments are not retrieved as normal strings to be printed but as the actual format codes fill, align and width.
    The arguments replaces the corresponding named placeholders and the string 'cat' is formatted accordingly.
  • Likewise, in the second example, 123.236 is the positional argument and, align, width and precision are passed to the template string as format codes.

Extra formatting options with format()

format() also supports type-specific formatting options like datetime's and complex number formatting.

format() internally calls __format__() for datetime, while format() accesses the attributes of the complex number.

You can easily override the __format__() method of any object for custom formatting.

Example 11: Type-specific formatting with format() and overriding __format__() method

 import datetime # datetime formatting date = datetime.datetime.now() print("It's now: (:%Y/%m/%d %H:%M:%S)".format(date)) # complex number formatting complexNumber = 1+2j print("Real part: (0.real) and Imaginary part: (0.imag)".format(complexNumber)) # custom __format__() method class Person: def __format__(self, format): if(format == 'age'): return '23' return 'None' print("Adam's age is: (:age)".format(Person()))

Output

 It's now: 2016/12/02 04:16:28 Real part: 1.0 and Imaginary part: 2.0 Adam's age is: 23 

Here,

  • For datetime:
    Current datetime is passed as a positional argument to the format() method.
    And, internally using __format__() method, format() accesses the year, month, day, hour, minutes and seconds.
  • For complex numbers:
    1+2j is internally converted to a ComplexNumber object.
    Then accessing its attributes real and imag, the number is formatted.
  • Overriding __format__():
    Like datetime, you can override your own __format__() method for custom formatting which returns age when accessed as (:age)

आप शॉर्टहैंड नोटेशन का उपयोग करके ऑब्जेक्ट की कार्यक्षमता __str__()और __repr__()कार्यक्षमता का भी उपयोग कर सकते हैं format()

जैसे __format__(), आप ऑब्जेक्ट __str__()और __repr_()विधियों को आसानी से ओवरराइड कर सकते हैं ।

उदाहरण 12: __str () __ और __repr () __ शॉर्टहैंड! R और! प्रारूप का उपयोग कर रहा है!)

 # __str__() and __repr__() shorthand !r and !s print("Quotes: (0!r), Without Quotes: (0!s)".format("cat")) # __str__() and __repr__() implementation for class class Person: def __str__(self): return "STR" def __repr__(self): return "REPR" print("repr: (p!r), str: (p!s)".format(p=Person()))

आउटपुट

 उद्धरण: 'कैट', विदाउट कोट्स: कैट रीप्र: आरईपीआर, स्ट्र: एसटीआर 

दिलचस्प लेख...