टेम्पलेट मेथड

Python में Regular Expressions

Maria Eugenia Inzaugarat

Data Scientist

टेम्पलेट strings

  • सिंटैक्स आसान
  • f-strings से धीमा
  • सीमित: format specifiers नहीं चलते
  • बाहरी रूप से फ़ॉर्मैट की गई strings के साथ अच्छा
Python में Regular Expressions

बेसिक सिंटैक्स

from string import Template

my_string = Template('Data science has been called $identifier')
my_string.substitute(identifier="sexiest job of the 21st century")
'Data science has been called sexiest job of the 21st century'
Python में Regular Expressions

Substitution

  • कई $identifier इस्तेमाल करें
  • वैरिएबल्स इस्तेमाल करें
from string import Template
job = "Data science"
name = "sexiest job of the 21st century"

my_string = Template('$title has been called $description')
my_string.substitute(title=job, description=name)
'Data science has been called sexiest job of the 21st century'
Python में Regular Expressions

Substitution

  • जब identifier के बाद valid कैरेक्टर आते हों तो ${identifier} इस्तेमाल करें

 

my_string = Template('I find Python very ${noun}ing but my sister has lost $noun')

my_string.substitute(noun="interest")
'I find Python very interesting but my sister has lost interest'
Python में Regular Expressions

Substitution

  • डॉलर साइन एस्केप करने के लिए $$ इस्तेमाल करें

 

my_string = Template('I paid for the Python course only $$ $price, amazing!')

my_string.substitute(price="12.50")
'I paid for the Python course only $ 12.50, amazing!'
Python में Regular Expressions

Substitution

  • Placeholder गुम हो तो error उठती है
favorite = dict(flavor="chocolate")

my_string = Template('I love $flavor $cake very much')
my_string.substitute(favorite)
Traceback (most recent call last):
KeyError: 'cake'
Python में Regular Expressions

Substitution

favorite = dict(flavor="chocolate")
my_string = Template('I love $flavor $cake very much')
try:
    my_string.substitute(favorite) 
except KeyError:
      print("missing information")
missing information
Python में Regular Expressions

Safe substitution

  • हमेशा एक usable string लौटाने की कोशिश करता है
  • गुम placeholders परिणाम में वैसे ही दिखेंगे
favorite = dict(flavor="chocolate")
my_string = Template('I love $flavor $cake very much')

my_string.safe_substitute(favorite)
'I love chocolate $cake very much'
Python में Regular Expressions

कौन सा इस्तेमाल करें?

  • str.format():

    • शुरुआत के लिए अच्छा. Concepts f-strings पर भी लागू होते हैं.
    • Python के सभी वर्ज़न से कम्पैटिबल.
  • f-strings:

    • बाकी तरीकों से बेहतर, सामान्यतः यही सलाह.
    • केवल modern Python वर्ज़न (3.6+) में उपयुक्त.
  • Template strings:

    • बाहरी या यूज़र-प्रोवाइडेड strings के साथ
Python में Regular Expressions

अभ्यास करते हैं!

Python में Regular Expressions

Preparing Video For Download...