- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Prefix matching in Python using pytrie module
In this article, we are going to learn about the pytrie module to prefix matching strings from a list of strings. Let's see an example to understand it clearly.
Input: List: ['tutorialspoint', 'tutorials', 'tutorialspython', 'python'] Prefix: 'tutorials' Output: ['tutorialspoint', 'tutorials', 'tutorialspython']
We can achieve it in different ways. In this tutorial, we are going to achieve it using the pytrie module.
From pytrie module, we will use the pytrie.StringTrie data structure. We can perform create, insert, search, and delete operations.
First, install the pytrie module with the following command.
pip install pytrie
Let's see steps to achieve the desired output.
- Import the pytrie module.
- Initialize the list, prefix.
- Create a trie data structure using pytrie.StringTrie().
- Iterate over the list and insert into the trie structure.
- And print the values matching given prefix.
Example
# importing the module import pytrie # initializing the list and prefix strings = ['tutorialspoint', 'tutorials', 'tutorialspython', 'python', 'learnpython'] prefix = 'tutorials' # creating an trie data structure trie = pytrie.StringTrie() # iterating over the list and adding it to trie for item in strings: trie[item] = item # printing the matched strings print(trie.values(prefix))
If you execute the above code, then you will get the following result.
Output
['tutorials', 'tutorialspoint', 'tutorialspython']
Conclusion
If you have any doubts in the tutorial, mention them in the comment section.
- Related Articles
- Template matching using OpenCV in Python
- Testing in Python using doctest module
- Prefix sum array in python using accumulate function
- Histograms Equalization using Python OpenCv Module
- ASCII art using Python pyfiglet module
- C++ Program to Find the Longest Prefix Matching of a Given Sequence
- K Prefix in Python
- Stack and Queue in Python using queue Module
- Documentation generation using the pydoc module in Python
- Reading an image using Python OpenCv module
- Python Generate QR Code using pyqrcode module?
- Wildcard Matching in Python
- Python - Plotting charts in excel sheet using openpyxl module
- Accessing the internet using the urllib.request module in Python
- Longest Common Prefix in Python

Advertisements