% String Formatting Operator
% एक String Formatting Operator या Interpolation Operator है। दिए गए format % values (जहां Format एक String है), Format में % Conversion Specifications को Values के Zero या अधिक Elements से Replace किया जाता है। Effect C Language में sprintf() का उपयोग करने के समान है।
Basic Examples:
>>> lang = "Python"
>>> print("%s is awesome!" % lang)
Python is awesome!
Number Formatting:
>>> cost = 128.527
>>> print("The book costs $%.2f at the bookstore" % cost)
The book costs $128.53 at the bookstore
Dictionary के साथ Interpolation:
आप Strings को Interpolate करने के लिए Dictionaries का भी उपयोग कर सकते हैं। इनका एक Syntax होता है जिसमें आपको % और Conversion Character के बीच Parentheses में Key Provide करना होता है।
print('%(language)s has %(number)03d quote types.' % {'language': "Python", "number": 2})
# Python has 002 quote types.
Common Format Specifiers:
| Specifier | Description |
|---|---|
%s |
String (str() का उपयोग) |
%r |
Repr (repr() का उपयोग) |
%d / %i |
Signed Integer |
%f |
Float (Default 6 Decimal Places) |
%.2f |
Float with 2 Decimals |
%x / %X |
Hexadecimal (Lower/Upper) |
%o |
Octal |
%e / %E |
Scientific Notation |
%% |
Literal % Character |
Multiple Values (Tuple Required):
>>> print("%s %s %d" % ("Hello", "World", 2024))
Hello World 2024
>>> print("%s %s %d" % "Hello") # Error - Tuple Expected
TypeError: not enough arguments for format string
Modern Alternatives:
str.format()- Python 2.6+f-strings- Python 3.6+ (Fastest, Most Readable)
अधिक जानकारी के लिए: Python String Formatting Docs