{"id":127988,"date":"2022-09-10T17:40:09","date_gmt":"2022-09-10T17:40:09","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=665034"},"modified":"2022-09-10T17:40:09","modified_gmt":"2022-09-10T17:40:09","slug":"how-to-find-a-partial-string-in-a-python-list","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2022\/09\/10\/how-to-find-a-partial-string-in-a-python-list\/","title":{"rendered":"How to Find a Partial String in a Python List?"},"content":{"rendered":"\n<div class=\"kk-star-ratings kksr-auto kksr-align-left kksr-valign-top\" data-payload=\"{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;665034&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;1&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\\\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\\\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}\">\n<div class=\"kksr-stars\">\n<div class=\"kksr-stars-inactive\">\n<div class=\"kksr-star\" data-star=\"1\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"2\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"3\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"4\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"5\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<div class=\"kksr-stars-active\" style=\"width: 142.5px;\">\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<\/div>\n<div class=\"kksr-legend\" style=\"font-size: 19.2px;\"> 5\/5 &#8211; (1 vote) <\/div>\n<\/div>\n<h2>Problem Formulation<\/h2>\n<p class=\"has-base-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f4ac.png\" alt=\"\ud83d\udcac\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Challenge<\/strong>: Given a Python list of strings and a query string. Find the strings that partially match the query string. <\/p>\n<p>Example 1:<\/p>\n<ul>\n<li><strong>Input<\/strong>: <code>['hello', 'world', 'python']<\/code> and <code>'pyth'<\/code><\/li>\n<li><strong>Output<\/strong>: <code>['python']<\/code><\/li>\n<\/ul>\n<p>Example 2: <\/p>\n<ul>\n<li><strong>Input<\/strong>: <code>['aaa', 'aa', 'a']<\/code> and <code>'a'<\/code><\/li>\n<li><strong>Output<\/strong>: <code>['aaa', 'aa', 'a']<\/code><\/li>\n<\/ul>\n<p>Example 3: <\/p>\n<ul>\n<li><strong>Input<\/strong>: <code>['aaa', 'aa', 'a']<\/code> and <code>'b'<\/code><\/li>\n<li><strong>Output<\/strong>: <code>[]<\/code><\/li>\n<\/ul>\n<p>Let&#8217;s dive into several methods that solve this and similar type of problems. We start with the most straightforward solution.<\/p>\n<h2>Method 1: Membership + List Comprehension<\/h2>\n<p class=\"has-global-color-8-background-color has-background\">The most Pythonic way to find a list of partial matches of a given string <code>query<\/code> in a string list <code>lst<\/code> is to use the membership operator <code>in<\/code> and the list comprehension statement like so: <code>[s for s in lst if query in s]<\/code>.<\/p>\n<p>Here&#8217;s a simple example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"2\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def partial(lst, query): return [s for s in lst if query in s] # Example 1:\nprint(partial(['hello', 'world', 'python'], 'pyth'))\n# ['python'] # Example 2:\nprint(partial(['aaa', 'aa', 'a'], 'a'))\n# ['aaa', 'aa', 'a'] # Example 3:\nprint(partial(['aaa', 'aa', 'a'], 'b'))\n# []\n<\/pre>\n<p>In case you need some background information, feel free to check out our two tutorials and the referenced videos.<\/p>\n<p class=\"has-base-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f449.png\" alt=\"\ud83d\udc49\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended Tutorial<\/strong>: <a href=\"https:\/\/blog.finxter.com\/list-comprehension\/\" data-type=\"post\" data-id=\"1171\" target=\"_blank\" rel=\"noreferrer noopener\">List Comprehension in Python<\/a><\/p>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube\"><a href=\"https:\/\/blog.finxter.com\/how-to-find-a-partial-string-in-a-python-list\/\"><img decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/plugins\/wp-youtube-lyte\/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2F9qsq2Vf48W8%2Fhqdefault.jpg\" alt=\"YouTube Video\"><\/a><figcaption><\/figcaption><\/figure>\n<p class=\"has-base-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f449.png\" alt=\"\ud83d\udc49\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended Tutorial<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-membership-in-operator\/\" data-type=\"post\" data-id=\"34005\" target=\"_blank\" rel=\"noreferrer noopener\">The Membership Operator in Python<\/a><\/p>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube\"><a href=\"https:\/\/blog.finxter.com\/how-to-find-a-partial-string-in-a-python-list\/\"><img decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/plugins\/wp-youtube-lyte\/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FoQkfuBAk9lo%2Fhqdefault.jpg\" alt=\"YouTube Video\"><\/a><figcaption><\/figcaption><\/figure>\n<h2>Method 2: list() and filter()<\/h2>\n<p class=\"has-global-color-8-background-color has-background\">To find a list of partial query matches given a string list <code>lst<\/code>, combine the <a href=\"https:\/\/blog.finxter.com\/python-membership-in-operator\/\" data-type=\"post\" data-id=\"34005\" target=\"_blank\" rel=\"noreferrer noopener\">membership operator<\/a> with the <code><a href=\"https:\/\/blog.finxter.com\/python-filter\/\" data-type=\"post\" data-id=\"22487\" target=\"_blank\" rel=\"noreferrer noopener\">filter()<\/a><\/code> function in which you pass a <a href=\"https:\/\/blog.finxter.com\/how-to-filter-in-python-using-lambda-functions\/\" data-type=\"post\" data-id=\"2976\" target=\"_blank\" rel=\"noreferrer noopener\">lambda function<\/a> that evaluates the membership operation for each element in the <a href=\"https:\/\/blog.finxter.com\/python-lists\/\" data-type=\"post\" data-id=\"7332\" target=\"_blank\" rel=\"noreferrer noopener\">list<\/a> like so: <code>list(filter(lambda x: query in x, lst))<\/code>.<\/p>\n<p>Here&#8217;s an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"2\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def partial(lst, query): return list(filter(lambda x: query in x, lst)) # Example 1:\nprint(partial(['hello', 'world', 'python'], 'pyth'))\n# ['python'] # Example 2:\nprint(partial(['aaa', 'aa', 'a'], 'a'))\n# ['aaa', 'aa', 'a'] # Example 3:\nprint(partial(['aaa', 'aa', 'a'], 'b'))\n# []\n<\/pre>\n<p>Beautiful <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-one-line-x\/\" data-type=\"post\" data-id=\"10612\" target=\"_blank\">Python one-liner<\/a>, isn&#8217;t it? <img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f984.png\" alt=\"\ud83e\udd84\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><\/p>\n<p>I recommend you check out the following tutorial with video to shed some light on the background information here:<\/p>\n<p class=\"has-base-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f449.png\" alt=\"\ud83d\udc49\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended Tutorial<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-filter\/\" data-type=\"post\" data-id=\"22487\" target=\"_blank\" rel=\"noreferrer noopener\">Python Filtering<\/a><\/p>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube\"><a href=\"https:\/\/blog.finxter.com\/how-to-find-a-partial-string-in-a-python-list\/\"><img decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/plugins\/wp-youtube-lyte\/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2F3nG4TLkqzf8%2Fhqdefault.jpg\" alt=\"YouTube Video\"><\/a><figcaption><\/figcaption><\/figure>\n<p>Generally, I like list comprehension more than the <code>filter()<\/code> function because the former is more concise (e.g., no need to <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-list\/\" data-type=\"post\" data-id=\"21502\" target=\"_blank\">convert<\/a> the result to a list) and slightly faster. But both work perfectly fine!<\/p>\n<h2>Method 3: Regex Match + List Comprehension<\/h2>\n<p class=\"has-global-color-8-background-color has-background\">The most flexible way to find a list of partial query matches given a string list <code>lst<\/code> is provided by Python&#8217;s powerful <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-regex\/\" data-type=\"post\" data-id=\"6210\" target=\"_blank\">regular expressions<\/a> functionality. For example, the expression <code>[x for x in lst if re.match(pattern, x)]<\/code> finds all strings that match a certain query pattern as defined by you.<\/p>\n<p>The following examples showcase this solution:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"1,4,5\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import re def partial(lst, query): pattern = '.*' + query + '.*' return [x for x in lst if re.match(pattern, x)] # Example 1:\nprint(partial(['hello', 'world', 'python'], 'pyth'))\n# ['python'] # Example 2:\nprint(partial(['aaa', 'aa', 'a'], 'a'))\n# ['aaa', 'aa', 'a'] # Example 3:\nprint(partial(['aaa', 'aa', 'a'], 'b'))\n# []\n<\/pre>\n<p>In this example, we use the dummy pattern <code>.*query.*<\/code> that simply matches words that contain the <code>query<\/code> string. However, you could also do more advanced pattern matching&#8212;regex to the rescue!<\/p>\n<p>Again, I&#8217;d recommend you check out the background info on regular expressions:<\/p>\n<p class=\"has-base-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f449.png\" alt=\"\ud83d\udc49\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended Tutorial<\/strong>: <a href=\"https:\/\/blog.finxter.com\/python-regex-match\/\" data-type=\"post\" data-id=\"5759\" target=\"_blank\" rel=\"noreferrer noopener\">Python Regex <code>match()<\/code> &#8212; A Simple Illustrated Guide<\/a><\/p>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube\"><a href=\"https:\/\/blog.finxter.com\/how-to-find-a-partial-string-in-a-python-list\/\"><img decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/plugins\/wp-youtube-lyte\/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2F5d3vQ8N0MJg%2Fhqdefault.jpg\" alt=\"YouTube Video\"><\/a><figcaption><\/figcaption><\/figure>\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n<h2>Regex Humor<\/h2>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full is-resized\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/06\/image-133.png\" alt=\"\" class=\"wp-image-428862\" width=\"700\" height=\"629\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/06\/image-133.png 785w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/06\/image-133-300x270.png 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/06\/image-133-768x691.png 768w\" sizes=\"auto, (max-width: 700px) 100vw, 700px\" \/><figcaption><em>Wait, forgot to escape a space. Wheeeeee[taptaptap]eeeeee.<\/em> (<a href=\"https:\/\/imgs.xkcd.com\/comics\/regular_expressions.png\" data-type=\"URL\" data-id=\"https:\/\/imgs.xkcd.com\/comics\/regular_expressions.png\" target=\"_blank\" rel=\"noreferrer noopener\">source<\/a>)<\/figcaption><\/figure>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>5\/5 &#8211; (1 vote) Problem Formulation Challenge: Given a Python list of strings and a query string. Find the strings that partially match the query string. Example 1: Input: [&#8216;hello&#8217;, &#8216;world&#8217;, &#8216;python&#8217;] and &#8216;pyth&#8217; Output: [&#8216;python&#8217;] Example 2: Input: [&#8216;aaa&#8217;, &#8216;aa&#8217;, &#8216;a&#8217;] and &#8216;a&#8217; Output: [&#8216;aaa&#8217;, &#8216;aa&#8217;, &#8216;a&#8217;] Example 3: Input: [&#8216;aaa&#8217;, &#8216;aa&#8217;, &#8216;a&#8217;] and [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-127988","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/127988","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=127988"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/127988\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=127988"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=127988"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=127988"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}