Back to all posts

Python String format()/f-string Method

Python में format() / f-string method का उपयोग Strings में वैल्यूज़ को dynamic तरीके से insert करने के लिए किया जाता है। यह एक बहुत ही powerful और readable…

Python में format()/f-string method का उपयोग Strings में वैल्यूज़ को dynamic तरीके से insert करने के लिए किया जाता है। यह एक बहुत ही powerful और readable तरीका है string formatting के लिए।


🔰 Example 1: Basic Variable Insertion

🔹 Using format():

Python
name = "Himanshu"
age = 25
print("My name is {} and I am {} years old.".format(name, age))

🔹 Using f-string:

Python
name = "Himanshu"
age = 25
print(f"My name is {name} and I am {age} years old.")

Explanation:

  • दोनों outputs same हैं।
  • लेकिन f-string ज़्यादा readable और short है।

🔰 Example 2: Positional Indexing

🔹 format():

Python
print("{0} scored {1} marks. Congratulations, {0}!".format("Himanshu", 95))

🔹 f-string (indexing की ज़रूरत नहीं):

Python
name = "Himanshu"
marks = 95
print(f"{name} scored {marks} marks. Congratulations, {name}!")

Explanation:

  • format() में index देना पड़ता है ताकि बार-बार use हो सके।
  • f-string में variable name direct use करने से code clear दिखता है।

🔰 Example 3: Named Placeholders

🔹 format():

Python
print("Name: {name}, Age: {age}".format(name="Himanshu", age=25))

🔹 f-string:

Python
name = "Himanshu"
age = 25
print(f"Name: {name}, Age: {age}")

Explanation:

  • format() में key-value pair देना होता है।
  • f-string में variable पहले से define हो और उसे {} में directly डाल सकते हैं।

🔰 Example 4: Decimal Formatting

🔹 format():

Python
pi = 3.14159265
print("Value of Pi: {:.2f}".format(pi))

🔹 f-string:

Python
pi = 3.14159265
print(f"Value of Pi: {pi:.2f}")

Explanation:

  • दोनों में decimal formatting आसान है।
  • f-string में format directly curly braces में ही हो जाता है।

🔰 Example 5: Expressions

🔹 format():

Python
a = 5
b = 3
print("Sum is: {}".format(a + b))

🔹 f-string:

Python
a = 5
b = 3
print(f"Sum is: {a + b}")

Explanation:

  • format() में expression को पहले calculate करना होता है या अंदर लिखा जाता है।
  • f-string में direct expression लिखा जा सकता है – {a + b}

🔚 Combined Explanation (संयुक्त रूप से समझिए):

विशेषता (Feature)format() Methodf-string
Syntaxलंबा और थोड़ा complexछोटा, clean और readable
Variables Insert करना.format(var1, var2)f"text {var1} text {var2}"
Reuse of VariablesIndex या name से करना पड़ता हैVariable को multiple बार आसानी से use कर सकते हैं
Decimal Formatting{:.2f} via format(){value:.2f} directly
Expression SupportLimited, manually calculate करना पड़ता हैDirectly {2 + 3} जैसा use कर सकते हैं
PerformanceSlowFastest (compiled internally)

✅ Final Tip:

  • Python 3.6+ का use कर रहे हैं? 👉 तो हमेशा f-string को प्राथमिकता दें।
  • Older Python version हो, या dynamic templates बना रहे हों? 👉 तब format() सही रहेगा।

Keep building your data skillset

Explore more SQL, Python, analytics, and engineering tutorials.