Python program to search for a pattern in string

Here, we will see a Python program to check if a pattern is present in a string or not. And then print all strings consisting of patterns from the array of string.
By Shivang Yadav Last updated : March 01, 2024

Python string is data structures that are immutable and are collections of characters in python. Array in python is a collection of data elements stored in consecutive memory locations. An array of strings is an array of multiple strings.

Source Code

Python program to search for a pattern in string

n=int(input("Enter number of cities : "))

city=()

for i in range(n):
    c=input("Enter City : ")
    city+=(c,)

print(city)

pat=input("Enter Pattern you want to search for? ")

for c in city:
    if(c.find(pat)!=-1):
        print(c)

Output

Enter number of cities : 5
Enter City : New Delhi
Enter City : New Mumbai
Enter City : Indore
Enter City : Gwalior
Enter City : Chennai
('New Delhi', 'New Mumbai', 'Indore', 'Gwalior', 'Chennai')
Enter Pattern you want to search for? New
New Delhi
New Mumbai

In the above code, we have created an array of strings named city to store names of cities and asked the user to enter names of cities. Then we asked the user to enter a pattern. Using the in method we have check for city names that match the pattern and printed the values.

To understand the above program, you should have the basic knowledge of the following Python topics:

Python String Programs »


Related Programs

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.