Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!
Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount
स्त्रिंग फॉर्मेटिंग
Python C-शैली के स्ट्रिंग फॉर्मेटिंग का उपयोग करके नए, फॉर्मेटेड स्ट्रिंग्स बनाने के लिए उपयोग करता है। "%" ऑपरेटर का उपयोग एक "tuple" (एक निश्चित आकार की सूची) में बंद किए गए वेरिएबल्स के सेट को फॉर्मेट करने के लिए किया जाता है, साथ ही एक फॉर्मेट स्ट्रिंग, जिसमें सामान्य पाठ और "argument specifiers", जैसे विशेष प्रतीक "%s" और "%d" शामिल होते हैं।
मान लीजिए आपके पास एक वेरिएबल है जिसका नाम "name" है और जिसमें आपका उपयोगकर्ता नाम है, और आप उस उपयोगकर्ता के लिए एक स्वागत संदेश प्रिंट करना चाहते हैं।
# यह "Hello, John!" प्रिंट करता है
name = "John"
print("Hello, %s!" % name)
दो या अधिक आर्ग्युमेंट स्पेसिफायर का उपयोग करने के लिए, एक tuple (ब्रैकेट) का उपयोग करें:
# यह "John is 23 years old." प्रिंट करता है
name = "John"
age = 23
print("%s is %d years old." % (name, age))
किसी भी ऑब्जेक्ट, जो स्ट्रिंग नहीं है, को भी %s ऑपरेटर का उपयोग करके फॉर्मेट किया जा सकता है। ऑब्जेक्ट के "repr" मेथड से प्राप्त होने वाली स्ट्रिंग को स्ट्रिंग के रूप में फॉर्मेट किया जाता है। उदाहरण के लिए:
# यह प्रिंट करता है: A list: [1, 2, 3]
mylist = [1,2,3]
print("A list: %s" % mylist)
यहाँ कुछ बुनियादी आर्ग्युमेंट स्पेसिफायर दिए गए हैं जिन्हें आपको जानना चाहिए:
%s - स्ट्रिंग (या किसी ऑब्जेक्ट का स्ट्रिंग प्रतिनिधित्व, जैसे कि संख्या)
%d - पूर्णांक
%f - फ्लोटिंग पॉइंट संख्या
%.<अंकों की संख्या>f - फ्लोटिंग पॉइंट संख्या जो डॉट के दाईं ओर निश्चित संख्या में अंक होती है।
%x/%X - हेक्स प्रतिनिधित्व में पूर्णांक (लोअरकेस/अपरकेस)
Exercise
आपको एक फॉर्मेट स्ट्रिंग लिखने की आवश्यकता होगी जो निम्नलिखित सिंटैक्स का उपयोग करके डेटा प्रिंट करे:
Hello John Doe. Your current balance is $53.44.
data = ("John", "Doe", 53.44)
format_string = "Hello"
print(format_string % data)
data = ("John", "Doe", 53.44)
format_string = "Hello %s %s. Your current balance is $%s."
print(format_string % data)
#test_output_contains("Hello John Doe. Your current balance is $53.44.", no_output_msg= "Make sure you add the `%s` in the correct spaces to the `format_string` to meeet the exercise goals!")
test_object('format_string')
success_msg('Great work!')
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!