Python में String Formatting
In this page:
"text {} {}".format(value1, value2)
f"text {variable}"
F-Strings
F-strings ज़्यादातर code में formatting के लिए modern, recommended default बनी हुई हैं -- यह section basics से एक level आगे जाता है, nested expressions, computed field widths, और format-spec mini-language की अन्य क्षमताओं पर focus करते हुए जिन्हें शुरुआत में miss करना आसान होता है।
उदाहरण: F-Strings
name = "Alex"
value = 3.14159
width = 10
print(f"{name:{width}}|{value:.2f}") # {width} is a nested field, .2f rounds to 2 decimals
format() Method
पहले cover किए गए साधारण .format() calls से आगे, format-spec mini-language जो यह f-strings के साथ share करती है, nested replacement fields को support करती है, जिससे width या precision खुद टेम्पलेट में hardcode होने के बजाय किसी variable से आ सकती है।
उदाहरण: The format() Method
value = 5
width = 8
print("{:{}}".format(value, width)) # the {} width itself comes from the second argument
Percentage Formatting (%)
Percent-style (%) formatting .format() और f-strings दोनों से पहले की है और अब भी कभी-कभी पुराने codebases या logging configuration में दिखती है, तो %s/%d/%f placeholders को पहचानना उपयोगी है भले ही आप नए code के लिए वह style न चुनें।
उदाहरण: Percentage Formatting (%)
name = "Alex"
age = 30
print("%s is %d years old" % (name, age)) # %s for the string, %d for the integer
Padding और Aligning
Alignment specifiers को computed widths के साथ जोड़ना -- जैसे f"{name:<{max_len}}" -- आपको ऐसे console tables बनाने देता है जो data की length अलग-अलग होने पर भी aligned रहते हैं, बजाय column की एक fixed width hardcode करने के।
उदाहरण: Padding and Aligning
names = ["Al", "Alexandra"]
max_len = max(len(n) for n in names) # widest name determines the column width
for name in names:
print(f"{name:<{max_len}}|") # left-align each name to that computed width
Decimals को Format करना
:.2f-style precision specifier सिर्फ़ दो decimal places तक सीमित नहीं है -- f से पहले की संख्या कोई भी digit count हो सकती है, और इसे comma (:,.2f) के साथ जोड़ना thousands separators add कर देता है, ये दोनों currency या बड़े statistics को साफ़-सुथरे तरीके से format करने के लिए उपयोगी हैं।
उदाहरण: Formatting Decimals
amount = 1234567.891
print(f"{amount:,.2f}")
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: