Pattern Matching in Python:-
Python में Pattern Matching एक ऐसी प्रक्रिया है, जिसमें किसी string के अंदर किसी विशेष character, word या substring को खोजा जाता है। इसका उपयोग text में किसी निश्चित pattern की उपस्थिति और स्थिति पता करने के लिए किया जाता है।
English : Pattern matching is the process of searching for a specific character, word, or substring within a string. It is used to find the presence and position of a particular pattern in text.
Python में basic pattern searching के लिए in, find(), index(), count() और startswith() जैसे operators और methods का उपयोग किया जा सकता है। अधिक complex patterns के लिए re module का उपयोग किया जाता है।
Example:
text = "Python is easy to learn"
if "easy" in text:
print("Pattern found")
else:
print("Pattern not found")
Output:
Pattern found
Explanation:
text एक string variable है।
"easy" in text जाँचता है कि "easy" substring string में मौजूद है या नहीं।
Pattern मिलने पर True और न मिलने पर False प्राप्त होता है।
Basic Pattern Searching :-
Basic Pattern Searching में किसी string के अंदर एक निश्चित character या substring को खोजा जाता है।
Example 1: Using the in Operator
in operator का उपयोग यह जाँचने के लिए किया जाता है कि कोई substring string में मौजूद है या नहीं।
English: The in operator checks whether a substring exists in a string.
Example:
text = "I am learning Python"
print("Python" in text)
print("Java" in text)
Output:
True
False
Example 2: Using find()
find() method substring की पहली occurrence का index return करता है। Substring नहीं मिलने पर -1 return करता है।
English: The find() method returns the index of the first occurrence of a substring. It returns -1 if the substring is not found.
Example:
text = "Python Programming"
print(text.find("Program"))
print(text.find("Java"))
Output:
7
-1
Example 3: Using count() -
count() method यह बताता है कि कोई substring string में कितनी बार आती है। यह overlapping occurrences को count नहीं करता।
English: The count() method returns the number of non-overlapping occurrences of a substring in a string.
Example:
text = "banana"
print(text.count("a"))
print(text.count("an"))
Output:
3
2
Example 4: Using startswith()
startswith() method जाँचता है कि string किसी विशेष substring से शुरू होती है या नहीं।
English: The startswith() method checks whether a string begins with a specified substring.
Example:
text = "Python Programming"
print(text.startswith("Python"))
print(text.startswith("Java"))
Output:
True
False