Python String Formatting
In this page:
"text %s and %d" % (string_value, integer_value)
"text {}".format(value)
f"text {variable}"
पुरानी % Formatting
% operator Python का सबसे पुराना string-formatting तरीका है, जो C की printf शैली से मिला है — "%s is %d" % (name, age) — और यह अब भी चलता है, पर काफ़ी हद तक नए, ज़्यादा पठनीय विकल्पों द्वारा हटा दिया गया है।
उदाहरण: Legacy % Formatting
name = "Alex"
age = 30
print("%s is %d" % (name, age)) # %s and %d are old-style C-like format specifiers
Format Styles की तुलना
Python तीन formatting तरीके देती है जिनके उद्देश्य आपस में मिलते हैं: % formatting (पुरानी, C-शैली), .format() (ज़्यादा लचीली, Python 2.6 में आई), और f-strings (सबसे नई और आमतौर पर सबसे तेज़, Python 3.6 से)। नए code के लिए f-strings ही अनुशंसित डिफ़ॉल्ट हैं।
उदाहरण: Comparing Format Styles
name, age = "Alex", 30
print("%s is %d" % (name, age)) # legacy % formatting
print("{} is {}".format(name, age)) # .format() method
print(f"{name} is {age}") # f-string, the modern recommended style
Template Strings
string.Template class braces या percent signs की जगह $name-शैली के placeholders इस्तेमाल करती है, और खास तौर पर तब ज़्यादा सुरक्षित होने के लिए बनी है जब template खुद किसी अविश्वसनीय स्रोत से आए, क्योंकि यह f-strings की तरह मनमानी expression evaluation को support नहीं करती।
उदाहरण: Template Strings
from string import Template
t = Template("$name is $age") # $name-style placeholders instead of {} or %s
print(t.substitute(name="Alex", age=30)) # fill placeholders by keyword
Multi-line String Formatting
Triple-quoted strings कई lines में फैल सकती हैं और फिर भी सामान्य रूप से format हो सकती हैं, जो बहु-line SQL queries, HTML के टुकड़े या configuration blocks को असुविधाजनक line-by-line concatenation के बिना सीधे Python code में डालने के लिए सुविधाजनक है।
उदाहरण: Multi-line String Formatting
name = "Alex"
message = f"""
Hello {name},
Welcome!
""" # triple-quoted f-string spans multiple lines
print(message)
String Formatting के सर्वोत्तम तरीके
ज़्यादातर formatting के लिए f-strings सही डिफ़ॉल्ट हैं क्योंकि वे तेज़ और पढ़ने में आसान हैं; string.Template तब इस्तेमाल कीजिए जब format string खुद user द्वारा दी गई हो, क्योंकि अविश्वसनीय f-string-शैली की expressions evaluate करना सुरक्षा जोखिम होगा।
उदाहरण: String Formatting Best Practices
name = "Alex"
print(f"{name} formatted with an f-string")
# Use string.Template instead when the template itself comes from untrusted input
Chapter Quiz — Complete all 16 topics to unlock
0/16 topics done
Complete these topics first:
- Python print()
- Python input()
- Python Format Strings
- Python f-strings
- Python String Formatting
- Python Arithmetic Operators
- Python Relational Operators
- Python Logical Operators
- Python Bitwise Operators
- Python Assignment Operators
- Python Increment & Decrement
- Python Ternary Operator
- Python Operator Precedence
- Python Identity Operators
- Python Membership Operators
- Python Operators