If tutorials available on this website are helpful for you, please whitelist this website in your ad blocker😭 or Donate to help us ❤️ pay for the web hosting to keep the website running.
Python tutorials पड़ते समय आपने कई examples में देखा होगा , कि print() function में किसी value / variable को print करने के लिए normally comma (,)For Example -
name = "Rahul" print("Hello", name)
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 में format() function का use करके string की formatting की जाती है, format() function में वो arguments pass किये जाते हैं, जिन्हे हमें string में print करना है। और उस string में curly brackets { } को छोड़ना होता है। -
name = "Rahul Kumar"
age = 24
txt = "Name : {} \nAge : {}"
print(txt.format(name, age))
C:\Users\Rahulkumar\Desktop\python>python format_str.py Name : Rahul 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))
C:\Users\Rahulkumar\Desktop\python>python format_str.py Name : Rahul Kumar Age : 24
अगर इससे भी आपको variables handle करने में कोई confusion होती है तो आप variables के name भी रख सकते हैं -
txt = "Name : {name} \nAge : {age}"
print(txt.format(name="Rahul Kumar", age=24))
C:\Users\Rahulkumar\Desktop\python>python format_str.py Name : Rahul Kumar Age : 24
I Hope, अब आपको python में string formatting अच्छे से समझ आ गया होगा।
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