Python tutorials पड़ते समय आपने कई examples में देखा होगा , कि print() function में किसी value / variable को print करने के लिए normally comma (,) का use करते हैं।

For Example -

name = "Learners" print("Hello", name)
Hello Learners

String Format मतलब need के according string में variables को सही जगह concatenate / add करना। बैसे तो आप string को plus (+) sign से concatenate कर सकते हैं , लेकिन वह सिर्फ string के लिए ही है। number और string को plus (+) sign से concatenate करने पर error generate हो जायगी।
See Example -

print("Hello"+" Rahul !") 
#Output : Hello Rahul !

#Now add string with number.

print("Age :"+ 23)
#It raises an error- 
Traceback (most recent call last):
  File "<str_format.py>", line 1, in <module>
    print("Age :"+ 23)
TypeError: must be str, not int

Python String format()

Python में format() function का use करके string की formatting की जाती है, format() function में वो arguments pass किये जाते हैं, जिन्हे हमें string में print करना है। और उस string में curly brackets { } को छोड़ना होता है। -

Python Format String Example

name = "Raju Kumar" age = 24 txt = "Name : {} \nAge : {}" print(txt.format(name, age))

Output

Name : Raju Kumar
Age : 24

Note : String में जितने curly brackets {} होंगे उतने ही आपको arguments pass करने पड़ेंगे , एक भी argument काम होने पर error generate होगी।

हालाँकि ऊपर define किये गए तरीके से formatting करते समय आपको pass किये जाने वाले arguments के order का ध्यान रखना पड़ता है।

इसके अलावा आप curly brackets {} में index number भी लिख सकते हैं , इससे आप किसी particular index का variable ही string में place हो पाएगा।
See Example -

name = "Rahul Kumar" age = 24 txt = "Name : {1} \nAge : {0}" print(txt.format(age, name))

अगर इससे भी आपको variables handle करने में कोई confusion होती है तो आप variables के name भी रख सकते हैं -

For ex.

txt = "Name : {name} \nAge : {age}" print(txt.format(name="Rahul Kumar", age=24))

Python f-String

F-String को Python 3.6 में introduce किया गया था , और इसकी help से आप बिना format() function का use किये directly string में variables को parse कर सकते हैं।

Python f-string example

movie = "Hera Pheri" characters = "Babu rao, Raju , Shyam" str = f"This is about {movie} movie, and the main characters are : {characters}" print(str)

Output

This is about Hera Pheri movie, and the main characters are : Babu rao, Raju , Shyam

तो देखा आपने F-String का use करके हम easily variables को parse कर सकते हैं।

I Hope, अब आपको python में string formatting अच्छे से समझ आ गया होगा।

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers