Dictionary के साथ String Formatting
आप Strings को Interpolate करने के लिए Dictionaries का उपयोग कर सकते हैं। इनका एक Syntax होता है जिसमें आपको % और Conversion Character के बीच Parentheses में Key Provide करना होता है।
उदाहरण
उदाहरण के लिए, यदि आपके पास Key 'cost' में Float Stored है और आप इसे '$xxxx.xx' के रूप में Format करना चाहते हैं, तो आप उस स्थान पर '$%(cost).2f' रखेंगे जहां आप इसे Display करना चाहते हैं।
>>> print('%(language)s has %(number)03d quote types.' % {'language': "Python", "number": 2})
Python has 002 quote types.
Complete Example:
data = {
'name': 'Alice',
'age': 30,
'city': 'New York',
'salary': 75000.50
}
# % Formatting
template = "Name: %(name)s, Age: %(age)d, City: %(city)s, Salary: $%(salary).2f"
print(template % data)
# Name: Alice, Age: 30, City: New York, Salary: $75000.50
Modern Alternatives (अनुशंसित):
1. str.format() with Dictionary Unpacking:
template = "Name: {name}, Age: {age}, City: {city}, Salary: ${salary:.2f}"
print(template.format(**data))
2. f-strings (Python 3.6+) - सबसे Fast और Readable:
name = data['name']
age = data['age']
city = data['city']
salary = data['salary']
print(f"Name: {name}, Age: {age}, City: {city}, Salary: ${salary:.2f}")
3. Template Strings (Safe, User-provided Templates के लिए):
from string import Template
template = Template("Name: $name, Age: $age")
print(template.substitute(data))
Format Specification Mini-Language:
# % Formatting "%(name)10s" # 10 chars wide, Right Align "%(name)-10s" # 10 chars wide, Left Align "%(num)05d" # 5 digits, Zero Padded "%(price).2f" # 2 Decimal Places "%(ratio).2%" # Percentage with 2 Decimals