पायथन स्ट्रिंग प्रारूप () विधि
उदाहरण
प्लेसहोल्डर के अंदर मूल्य डालें, कीमत निश्चित बिंदु, दो-दशमलव प्रारूप में होनी चाहिए:
txt = "For only {price:.2f} dollars!"
print(txt.format(price = 49))
परिभाषा और उपयोग
विधि निर्दिष्ट मान (मानों) को format()
प्रारूपित करती है और उन्हें स्ट्रिंग के प्लेसहोल्डर के अंदर सम्मिलित करती है।
प्लेसहोल्डर को घुंघराले कोष्ठक का उपयोग करके परिभाषित किया गया है: {}। नीचे प्लेसहोल्डर अनुभाग में प्लेसहोल्डर के बारे में और पढ़ें।
format()
विधि स्वरूपित स्ट्रिंग लौटाती है ।
वाक्य - विन्यास
string.format(value1, value2...)
पैरामीटर मान
Parameter | Description |
---|---|
value1, value2... | Required. One or more values that should be formatted and inserted in
the string. The values are either a list of values separated by commas, a key=value list, or a combination of both. The values can be of any data type. |
प्लेसहोल्डर
{price}
प्लेसहोल्डर्स को नामित इंडेक्स , क्रमांकित इंडेक्स {0}
, या यहां तक कि खाली प्लेसहोल्डर
का उपयोग करके पहचाना जा सकता है
{}
।
उदाहरण
विभिन्न प्लेसहोल्डर मानों का उपयोग करना:
txt1 = "My
name is {fname}, I'm {age}".format(fname = "John", age = 36)
txt2 = "My
name is {0}, I'm {1}".format("John",36)
txt3 = "My
name is {}, I'm {}".format("John",36)
स्वरूपण प्रकार
प्लेसहोल्डर्स के अंदर आप परिणाम स्वरूपित करने के लिए एक स्वरूपण प्रकार जोड़ सकते हैं:
:< |
Left aligns the result (within the available space) | |
:> |
Right aligns the result (within the available space) | |
:^ |
Center aligns the result (within the available space) | |
:= |
Places the sign to the left most position | |
:+ |
Use a plus sign to indicate if the result is positive or negative | |
:- |
Use a minus sign for negative values only | |
: |
Use a space to insert an extra space before positive numbers (and a minus sign before negative numbers) | |
:, |
Use a comma as a thousand separator | |
:_ |
Use a underscore as a thousand separator | |
:b |
Binary format | |
:c |
Converts the value into the corresponding unicode character | |
:d |
Decimal format | |
:e |
Scientific format, with a lower case e | |
:E |
Scientific format, with an upper case E | |
:f |
Fix point number format | |
:F |
Fix point number format, in uppercase format (show
inf and
nan as INF
and NAN ) |
|
:g |
General format | |
:G |
General format (using a upper case E for scientific notations) | |
:o |
Octal format | |
:x |
Hex format, lower case | |
:X |
Hex format, upper case | |
:n |
Number format | |
:% |
Percentage format |