{"id":703,"date":"2018-04-29T06:47:45","date_gmt":"2018-04-29T06:47:45","guid":{"rendered":"http:\/\/www.afternerd.com\/blog\/?p=703"},"modified":"2020-05-25T13:16:00","modified_gmt":"2020-05-25T13:16:00","slug":"python-string-contains","status":"publish","type":"post","link":"https:\/\/www.afternerd.com\/blog\/python-string-contains\/","title":{"rendered":"How to Check if a Python String Contains Another String?"},"content":{"rendered":"<p>One of the most common operations that programmers use on strings is to check whether a string contains some other string.<\/p>\n<p>If you are coming to Python from Java, for instance, you might have used the <a href=\"https:\/\/www.javatpoint.com\/java-string-contains\" target=\"_blank\" rel=\"noopener noreferrer\"><strong>contains<\/strong><\/a> method to check if some substring exists in another string.<\/p>\n<p>In Python, there are two ways to achieve this.<\/p>\n<h2>First: Using the in operator<\/h2>\n<p>The easiest way is via Python&#8217;s <span class=\"symbol\">in<\/span> operator.<\/p>\n<p>Let&#8217;s take a look at this example.<\/p>\n<pre class=\"prettyprint\"><code>&gt;&gt;&gt; str = \"Messi is the best soccer player\"\r\n&gt;&gt;&gt; \"soccer\" in str\r\nTrue\r\n&gt;&gt;&gt; \"football\" in str\r\nFalse<\/code><\/pre>\n<p>As you can see, the in operator returns True when the substring exists in the string.<\/p>\n<p>Otherwise, it returns false.<\/p>\n<p>This method is very straightforward, clean, readable, and idiomatic.<\/p>\n<h2>Second: Using the find method<\/h2>\n<p>Another method you can use is the <a href=\"https:\/\/www.tutorialspoint.com\/python\/string_find.htm\" target=\"_blank\" rel=\"noopener noreferrer\">string&#8217;s find method<\/a>.<\/p>\n<p>Unlike the in operator which is evaluated to a boolean value, the <span class=\"symbol\">find<\/span> method returns an integer.<\/p>\n<p>This integer is essentially the index of the beginning of the substring if the substring exists, otherwise -1 is returned.<\/p>\n<p>Let&#8217;s see the <span class=\"symbol\">find<\/span> method in action.<\/p>\n<pre class=\"prettyprint\"><code>&gt;&gt;&gt; str = \"Messi is the best soccer player\"\r\n&gt;&gt;&gt; str.find(\"soccer\")\r\n18\r\n&gt;&gt;&gt; str.find(\"Ronaldo\")\r\n-1\r\n&gt;&gt;&gt; str.find(\"Messi\")\r\n0<\/code><\/pre>\n<p>One cool thing about this method is you can optionally specify a start index and an end index to limit your search within.<\/p>\n<p>For example<\/p>\n<pre class=\"prettyprint\"><code>&gt;&gt;&gt; str = \"Messi is the best soccer player\"\r\n&gt;&gt;&gt; str.find(\"soccer\", 5, 25)\r\n18\r\n&gt;&gt;&gt; str.find(\"Messi\", 5, 25)\r\n-1<\/code><\/pre>\n<p>Notice how a -1 was returned for <span class=\"symbol\">&#8220;Messi&#8221;<\/span> because you are limiting your search to the string between indices 5 and 25 only.<\/p>\n<div class=\"after-post-box\">\n<h2>Python 3 Cheat Sheet for Beginners<\/h2>\n<p><img decoding=\"async\" style=\"border: 5px solid #f18225\" src=\"https:\/\/www.afternerd.com\/blog\/wp-content\/uploads\/2020\/05\/Screen-Shot-2020-05-24-at-8.42.42-AM.png\"><\/p>\n<p>Download a comprehensive cheat sheet for beginners with extensive code examples that covers all the topics that you need to learn.<br \/>\n<script type=\"text\/javascript\" src=\"\/\/mautic.afternerd.com\/form\/generate.js?id=9\"><\/script>\n<\/div>\n\n<h2>Some Advanced Stuff<\/h2>\n<p>Assume for a second that Python has no built-in functions or methods that would check if a string contains another string.<\/p>\n<p>How would you write a function to do that?<\/p>\n<p>Well, an easy way is to brute force by checking if the substring exists starting from every possible position in the original string.<\/p>\n<p>For larger strings, this process can be really slow.<\/p>\n<p>There are better algorithms for string searching.<\/p>\n<p>I highly recommend this article from TopCoder if you want to learn more and <a href=\"https:\/\/www.topcoder.com\/community\/data-science\/data-science-tutorials\/introduction-to-string-searching-algorithms\/\" target=\"_blank\" rel=\"noopener noreferrer\">dive deeper into string searching algorithms<\/a>.<\/p>\n<p>For more coverage of other string searching algorithms not covered in the previous article, <a href=\"https:\/\/en.wikipedia.org\/wiki\/String_searching_algorithm\" target=\"_blank\" rel=\"noopener noreferrer\">this wikipedia page is great<\/a>.<\/p>\n<p>If you go through the previous articles and study them, your next question would be &#8220;well what algorithm does Python actually use?&#8221;<\/p>\n<p>These kinds of questions almost always require digging into the source code.<\/p>\n<p>But you are in luck because Python&#8217;s implementation is open source.<\/p>\n<p>Alright, let&#8217;s <a href=\"https:\/\/github.com\/python\/cpython\" target=\"_blank\" rel=\"noopener noreferrer\">dig into the code<\/a>.<\/p>\n<p>&nbsp;<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-707\" src=\"http:\/\/www.afternerd.com\/blog\/wp-content\/uploads\/2018\/04\/Screen-Shot-2018-04-28-at-11.03.59-PM.png\" alt=\"\" width=\"2054\" height=\"1298\" srcset=\"https:\/\/www.afternerd.com\/blog\/wp-content\/uploads\/2018\/04\/Screen-Shot-2018-04-28-at-11.03.59-PM.png 2054w, https:\/\/www.afternerd.com\/blog\/wp-content\/uploads\/2018\/04\/Screen-Shot-2018-04-28-at-11.03.59-PM-300x190.png 300w, https:\/\/www.afternerd.com\/blog\/wp-content\/uploads\/2018\/04\/Screen-Shot-2018-04-28-at-11.03.59-PM-768x485.png 768w, https:\/\/www.afternerd.com\/blog\/wp-content\/uploads\/2018\/04\/Screen-Shot-2018-04-28-at-11.03.59-PM-1024x647.png 1024w, https:\/\/www.afternerd.com\/blog\/wp-content\/uploads\/2018\/04\/Screen-Shot-2018-04-28-at-11.03.59-PM-320x202.png 320w, https:\/\/www.afternerd.com\/blog\/wp-content\/uploads\/2018\/04\/Screen-Shot-2018-04-28-at-11.03.59-PM-700x441.png 700w, https:\/\/www.afternerd.com\/blog\/wp-content\/uploads\/2018\/04\/Screen-Shot-2018-04-28-at-11.03.59-PM-200x126.png 200w, https:\/\/www.afternerd.com\/blog\/wp-content\/uploads\/2018\/04\/Screen-Shot-2018-04-28-at-11.03.59-PM-400x253.png 400w, https:\/\/www.afternerd.com\/blog\/wp-content\/uploads\/2018\/04\/Screen-Shot-2018-04-28-at-11.03.59-PM-600x379.png 600w, https:\/\/www.afternerd.com\/blog\/wp-content\/uploads\/2018\/04\/Screen-Shot-2018-04-28-at-11.03.59-PM-800x506.png 800w, https:\/\/www.afternerd.com\/blog\/wp-content\/uploads\/2018\/04\/Screen-Shot-2018-04-28-at-11.03.59-PM-1200x758.png 1200w\" sizes=\"(max-width: 2054px) 100vw, 2054px\" \/><\/p>\n<p>Perfect, I am happy the developers commented their code \ud83d\ude42<\/p>\n<p>It is very clear now that the find method uses a mix of <a href=\"https:\/\/en.wikipedia.org\/wiki\/Boyer%E2%80%93Moore_string_search_algorithm\" target=\"_blank\" rel=\"noopener noreferrer\">boyer-moore<\/a> and <a href=\"https:\/\/en.wikipedia.org\/wiki\/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm\" target=\"_blank\" rel=\"noopener noreferrer\">horspool<\/a> algorithms.<\/p>\n<h2>Conclusion<\/h2>\n<p>You can use the <span class=\"symbol\">in<\/span> operator or the string&#8217;s <span class=\"symbol\">find<\/span> method to check if a string contains another string.<\/p>\n<p>The <span class=\"symbol\">in<\/span> operator returns True if the substring exists in the string. Otherwise, it returns False.<\/p>\n<p>The <span class=\"symbol\">find<\/span> method returns the index of the beginning of the substring if found, otherwise -1 is returned.<\/p>\n<p>Python&#8217;s implementation (CPython) uses a mix of <strong>boyer-moore<\/strong> and <strong>horspool<\/strong> for string searching.<\/p>\n<h3>Learning Python?<\/h3>\n<p>Check out <a href=\"https:\/\/courses.afternerd.com\/\">the Courses section!<\/a><\/p>\n\n<h2>Featured Posts<\/h2>\n<ul>\n<li><a href=\"https:\/\/www.afternerd.com\/blog\/learn-python\/\">The Python Learning Path (From Beginner to Mastery)<\/a><\/li>\n<li><a href=\"https:\/\/www.afternerd.com\/blog\/learn-computer-science\/\">Learn Computer Science (From Zero to Hero)<\/a><\/li>\n<li><a href=\"https:\/\/www.afternerd.com\/blog\/coding-interview\/\">Coding Interview Preparation Guide<\/a><\/li>\n<li><a href=\"https:\/\/www.afternerd.com\/blog\/stock-investing-for-beginners\/\">The Programmer&#8217;s Guide to Stock Market Investing<\/a><\/li>\n<li><a href=\"https:\/\/www.afternerd.com\/blog\/start-programming-blog\/\">How to Start Your Programming Blog?<\/a><\/li>\n<\/ul>\n<div class=\"after-post-box\">\n<h2>Are you Beginning your Programming Career?<\/h2>\n<h3>I provide my best content for beginners in the newsletter.<\/h3>\n<ul>\n<li>Python tips for beginners, intermediate, and advanced levels.<\/li>\n<li>CS Career tips and advice.<\/li>\n<li>Special discounts on my premium courses when they launch.<\/li>\n<\/ul>\n<p>And so much more&#8230;<\/p>\n<h3>Subscribe now. It&#8217;s Free.<\/h3>\n<p><script type=\"text\/javascript\" src=\"\/\/mautic.afternerd.com\/form\/generate.js?id=2\"><\/script><\/p>\n<\/div>\n\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":1,"featured_media":709,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[12],"tags":[13],"yst_prominent_words":[497,503,1628,475,471,478,496,490,501,502,493,1629,421,483,486,488,469,474,499,500],"_links":{"self":[{"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/posts\/703"}],"collection":[{"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/comments?post=703"}],"version-history":[{"count":40,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/posts\/703\/revisions"}],"predecessor-version":[{"id":1845,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/posts\/703\/revisions\/1845"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/media\/709"}],"wp:attachment":[{"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/media?parent=703"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/categories?post=703"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/tags?post=703"},{"taxonomy":"yst_prominent_words","embeddable":true,"href":"https:\/\/www.afternerd.com\/blog\/wp-json\/wp\/v2\/yst_prominent_words?post=703"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}