← Back to Python Course | Chapter 5: Strings | Lesson 4 of 6

Python में String Formatting

String formatting किसी वाक्य के खाली हिस्सों को अपनी values से भरने जैसा है। Python इसे कई तरीकों से करने देता है ताकि messages बिल्कुल सही दिखें।
Syntax
python
"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

python
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

python
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 (%)

python
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

python
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

python
amount = 1234567.891
print(f"{amount:,.2f}")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.