Formatted Output (f-Strings) / फॉर्मेटेड आउटपुट (f-Strings) :-
Formatted Output (f-Strings) Python में String Formatting का सबसे आधुनिक, सरल और तेज़ तरीका है। इसकी सहायता से Variables, Expressions तथा Function के परिणामों को सीधे String के अंदर प्रदर्शित किया जा सकता है।
Python में f-String की शुरुआत Python 3.6 से हुई।
महत्वपूर्ण (Exam Point):
f-String में Variable या Expression हमेशा Curly Braces {} के अंदर लिखा जाता है।
English
Formatted Output (f-Strings) is the modern, easiest, and fastest way to format strings in Python. It allows variables, expressions, and function results to be inserted directly into a string.
f-Strings were introduced in Python 3.6.
Important (Exam Point):
Variables or expressions are always written inside Curly Braces {}.
Syntax -
f"Text {variable}"
or
f"Text {expression}"
Explanation -
f - Indicates that the string is an f-String.
" " - String enclosed in quotes.
{ } - Used to insert variables or expressions.
Example 1 : Printing Variables:-
name = "Rahul"
age = 18
print(f"My name is {name}.")
print(f"I am {age} years old.")
Output -
My name is Rahul.
I am 18 years old.
Explanation -
Variable को {} के अंदर लिखने पर उसकी Value Print होती है।
Example 2 : Multiple Variables:-
name = "Amit"
course = "Python"
marks = 95
print(f"{name} scored {marks} marks in {course}.")
Output -
Amit scored 95 marks in Python.
Explanation -
एक ही String में कई Variables का उपयोग किया जा सकता है।
Example 3 : Mathematical Expressions ⭐ (Most Important):-
a = 15
b = 5
print(f"Addition = {a+b}")
print(f"Subtraction = {a-b}")
print(f"Multiplication = {a*b}")
print(f"Division = {a/b}")
Output -
Addition = 20
Subtraction = 10
Multiplication = 75
Division = 3.0
Explanation -
Curly Braces के अंदर पूरा Mathematical Expression लिखा जा सकता है।
Example 4 : Function Call -
name = "python"
print(f"Upper Case = {name.upper()}")
print(f"Length = {len(name)}")
Upper Case = PYTHON
Length = 6
Explanation -
Functions को भी सीधे {} के अंदर लिखा जा सकता है।
Example 5 : Decimal Formatting -
pi = 3.14159265
print(f"{pi:.2f}") # 2 digits after decimal
print(f"{pi:.3f}") # 3 digits after decimal
Output:-
3.14
3.142
Example 6 : Width Formatting -
num = 25
print(f"|{num:5}|")
Output -
| 25|
Explanation -
5 का अर्थ है कि Number के लिए कुल 5 Characters की जगह Reserve की जाएगी।
Example 7 : Alignment -
name = "Ram"
print(f"|{name:<10}|") # Left
print(f"|{name:^10}|") # Center
print(f"|{name:>10}|") # Right
Output -
|Ram |
| Ram |
| Ram|
Example 8 : Leading Zero -
roll = 25
print(f"{roll:05}")
Output -
00025