{"cells":[{"cell_type":"markdown","id":"48ec64d3-3d71-46ca-b30e-f6c262714455","metadata":{},"outputs":[],"source":["<center>\n","    <img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/IDSNlogo.png\" width=\"300\" alt=\"cognitiveclass.ai logo\">\n","</center>\n","\n","# String Operations\n","\n","Estimated time needed: **30** minutes.\n","\n","## Objectives\n","\n","After completing this lab you will be able to:\n","\n","*   Work with Strings\n","*   Perform operations on String\n","*   Manipulate Strings using indexing and escape sequences\n"]},{"cell_type":"markdown","id":"e90c418c-a7b4-4bcb-8af2-5a494cdca938","metadata":{},"outputs":[],"source":["<h2>Table of Contents</h2>\n","<div class=\"alert alert-block alert-info\" style=\"margin-top: 20px\">\n","    <ul>\n","        <li>\n","            <a href=\"#What-are-Strings?\">What are Strings?</a>\n","        </li>\n","        <li>\n","            <a href=\"#Indexing\">Indexing</a>\n","            <ul>\n","                <li><a href=\"#Negative-Indexing\">Negative Indexing</a></li>\n","                <li><a href=\"#Slicing\">Slicing</a></li>\n","                <li><a href=\"#Stride\">Stride</a></li>\n","                <li><a href=\"#Concatenate-Strings\">Concatenate Strings</a></li>\n","            </ul>\n","        </li>\n","        <li>\n","            <a href=\"#Escape-Sequences\">Escape Sequences</a>\n","        </li>\n","        <li>\n","            <a href=\"#String-Manipulation-Operations\">String Manipulation Operations</a>\n","        </li>\n","        <li>\n","            <a href=\"#Quiz-on-Strings\">Quiz on Strings</a>\n","        </li>\n","    </ul>\n","\n","</div>\n","\n","<hr>\n"]},{"cell_type":"markdown","id":"e2cfb984-f2f4-4524-8b21-3791ce4068a7","metadata":{},"outputs":[],"source":["## What are Strings?\n"]},{"cell_type":"markdown","id":"d9102547-2e49-4cf1-aa7c-fc1ec6baed26","metadata":{},"outputs":[],"source":["The following example shows a string contained within 2 quotation marks:\n"]},{"cell_type":"code","id":"02a99580-c3f0-4890-8bfa-ebe49fa06957","metadata":{},"outputs":[],"source":["# Use quotation marks for defining string\n\n\"Michael Jackson\""]},{"cell_type":"markdown","id":"908b14e3-91cd-4e6a-927d-c6aebd079bc9","metadata":{},"outputs":[],"source":["We can also use single quotation marks:\n"]},{"cell_type":"code","id":"9e99a3c7-ab74-429c-8338-2a994dcabe95","metadata":{},"outputs":[],"source":["# Use single quotation marks for defining string\n\n'Michael Jackson'"]},{"cell_type":"markdown","id":"16da126a-ade8-4b06-bc07-756e64203920","metadata":{},"outputs":[],"source":["A string can be a combination of spaces and digits:\n"]},{"cell_type":"code","id":"f7a4239f-c91e-443d-b554-08a8d8669946","metadata":{},"outputs":[],"source":["# Digitals and spaces in string\n\n'1 2 3 4 5 6 '"]},{"cell_type":"markdown","id":"5580dbb1-5d5c-4f7e-ad28-234c6c1bcb93","metadata":{},"outputs":[],"source":["A string can also be a combination of special characters :\n"]},{"cell_type":"code","id":"28db5d23-14cc-4b66-9357-c10864d8f6d3","metadata":{},"outputs":[],"source":["# Special characters in string\n\n'@#2_#]&*^%$'"]},{"cell_type":"markdown","id":"de99b4a4-d0bf-4540-9726-90e1b778036b","metadata":{},"outputs":[],"source":["We can print our string using the print statement:\n"]},{"cell_type":"code","id":"d08d7b52-a5c3-48c5-a0b0-ead64035f123","metadata":{},"outputs":[],"source":["# Print the string\n\nprint(\"hello!\")"]},{"cell_type":"markdown","id":"2fb0fde1-7983-4cdb-a1f1-81f031024953","metadata":{},"outputs":[],"source":["We can bind or assign a string to another variable:\n"]},{"cell_type":"code","id":"1834d54e-4cca-421e-a8f9-921e01b8a5d2","metadata":{},"outputs":[],"source":["# Assign string to variable\n\nname = \"Michael Jackson\"\nname"]},{"cell_type":"markdown","id":"09b0106c-8625-4441-bb03-09ff2f82d38b","metadata":{},"outputs":[],"source":["<hr>\n"]},{"cell_type":"markdown","id":"0a5f7694-08f4-4d5d-b6ae-a2573398bb53","metadata":{},"outputs":[],"source":["## Indexing\n"]},{"cell_type":"markdown","id":"4f5e72a2-4d9c-4fa8-b47f-9824761d5a24","metadata":{},"outputs":[],"source":["It is helpful to think of a string as an ordered sequence. Each element in the sequence can be accessed using an index represented by the array of numbers:\n"]},{"cell_type":"markdown","id":"7b33d855-7e0a-4c45-9920-8c36e52c675c","metadata":{},"outputs":[],"source":["<img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%201/images/StringsIndex.png\" width=\"600\" align=\"center\">\n"]},{"cell_type":"markdown","id":"ead27ebd-97b9-4295-b7f8-775ee3ea4846","metadata":{},"outputs":[],"source":["The first index can be accessed as follows:\n"]},{"cell_type":"markdown","id":"035f9ff7-6d69-40e2-808e-471640083de9","metadata":{},"outputs":[],"source":["<hr/>\n","<div class=\"alert alert-success alertsuccess\" style=\"margin-top: 20px\">\n","[Tip]: Because indexing starts at 0, it means the first index is on the index 0.\n","</div>\n","<hr/>\n"]},{"cell_type":"code","id":"8534fb3e-753f-4888-a2ca-f82867891848","metadata":{},"outputs":[],"source":["# Print the first element in the string\n\nprint(name[0])"]},{"cell_type":"markdown","id":"7f864c9d-8f52-49e7-8425-9a63a80cdaec","metadata":{},"outputs":[],"source":["We can access index 6:\n"]},{"cell_type":"code","id":"5c0157f5-3af6-474c-86df-a18c60f69bbd","metadata":{},"outputs":[],"source":["# Print the element on index 6 in the string\n\nprint(name[6])"]},{"cell_type":"markdown","id":"a6ddb2a2-3f01-4ee2-96c0-47a6395964a4","metadata":{},"outputs":[],"source":["Moreover, we can access the 13th index:\n"]},{"cell_type":"code","id":"6be76af2-1593-465b-862f-220ae85572ac","metadata":{},"outputs":[],"source":["# Print the element on the 13th index in the string\n\nprint(name[13])"]},{"cell_type":"markdown","id":"f84da932-894f-4e08-9feb-48abbed70011","metadata":{},"outputs":[],"source":["### Negative Indexing\n"]},{"cell_type":"markdown","id":"f70032d2-b704-4fca-bcf7-58b074ab031a","metadata":{},"outputs":[],"source":["We can also use negative indexing with strings:\n"]},{"cell_type":"markdown","id":"92396736-9a55-49fe-bd7b-7a2c5a234ef8","metadata":{},"outputs":[],"source":["<img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%201/images/StringsNeg.png\" width=\"600\" align=\"center\">\n"]},{"cell_type":"markdown","id":"3b39f9e3-8da6-420a-a203-7d5a3d063462","metadata":{},"outputs":[],"source":["Negative index can help us to count the element from the end of the string.\n"]},{"cell_type":"markdown","id":"3e4b2333-e407-49c2-b903-e176c2e3b29f","metadata":{},"outputs":[],"source":["The last element is given by the index -1:\n"]},{"cell_type":"code","id":"f8c67207-2a52-41bd-b13d-9b06d1a45c97","metadata":{},"outputs":[],"source":["# Print the last element in the string\n\nprint(name[-1])"]},{"cell_type":"markdown","id":"cf4ef532-3d16-4ddb-88fe-a4b61d1642b1","metadata":{},"outputs":[],"source":["The first element can be obtained by  index -15:\n"]},{"cell_type":"code","id":"d9023310-3a44-4726-b29d-21ca9debf30d","metadata":{},"outputs":[],"source":["# Print the first element in the string\n\nprint(name[-15])"]},{"cell_type":"markdown","id":"e6ed6a5a-737f-4627-99a0-209b26ce6587","metadata":{},"outputs":[],"source":["We can find the number of characters in a string by using <code>len</code>, short for length:\n"]},{"cell_type":"code","id":"3d0b9c8c-1914-43e6-8fc2-2b43a4643080","metadata":{},"outputs":[],"source":["# Find the length of string\n\nlen(\"Michael Jackson\")"]},{"cell_type":"markdown","id":"4e17c2b4-776c-4b14-a0f5-0b67f8553485","metadata":{},"outputs":[],"source":["### Slicing\n"]},{"cell_type":"markdown","id":"8969e5c7-72ab-46fe-88e6-19ff3d240ff4","metadata":{},"outputs":[],"source":["We can obtain multiple characters from a string using slicing, we can obtain the 0 to 4th and 8th to the 12th element:\n"]},{"cell_type":"markdown","id":"6b657b19-858a-4e5b-944b-5c5595fee19d","metadata":{},"outputs":[],"source":["<img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%201/images/StringsSlice.png\" width=\"600\" align=\"center\">\n"]},{"cell_type":"markdown","id":"7ab59658-5689-425d-bfb2-47be5877867e","metadata":{},"outputs":[],"source":["<hr/>\n","<div class=\"alert alert-success alertsuccess\" style=\"margin-top: 20px\">\n","[Tip]: When taking the slice, the first number means the index (start at 0), and the second number means the length from the index to the last element you want (start at 1)\n","</div>\n","<hr/>\n"]},{"cell_type":"code","id":"72f2d269-ddf9-4194-942f-c41fd99375b8","metadata":{},"outputs":[],"source":["# Take the slice on variable name with only index 0 to index 3\n\nname[0:4]"]},{"cell_type":"code","id":"908534fe-90ca-48d9-b4a0-8dd5c43b0e2e","metadata":{},"outputs":[],"source":["# Take the slice on variable name with only index 8 to index 11\n\nname[8:12]"]},{"cell_type":"markdown","id":"79a4c8db-a972-433a-86a5-73920f652abe","metadata":{},"outputs":[],"source":["### Stride\n"]},{"cell_type":"markdown","id":"c8a864b8-ab3c-4519-8785-fc9f7e137027","metadata":{},"outputs":[],"source":["We can also input a stride value as follows, with the '2' indicating that we are selecting every second variable:\n"]},{"cell_type":"markdown","id":"b20d1b31-3e70-40f6-8b3d-d992fcf3eb77","metadata":{},"outputs":[],"source":["<img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%201/images/StringsStride.png\" width=\"600\" align=\"center\">\n"]},{"cell_type":"code","id":"afb9fb46-17f8-4db1-885f-a94197f52427","metadata":{},"outputs":[],"source":["# Get every second element. The elments on index 1, 3, 5 ...\n\nname[::2]"]},{"cell_type":"markdown","id":"01ed2f39-c512-4943-84b5-46cc5198d195","metadata":{},"outputs":[],"source":["We can also incorporate slicing  with the stride. In this case, we select the first five elements and then use the stride:\n"]},{"cell_type":"code","id":"6fd4928c-f76c-43f9-9e62-4d0a29cecd14","metadata":{},"outputs":[],"source":["# Get every second element in the range from index 0 to index 4\n\nname[0:5:2]"]},{"cell_type":"markdown","id":"70220319-854c-482f-bfa7-96f61dd1f59f","metadata":{},"outputs":[],"source":["### Concatenate Strings\n"]},{"cell_type":"markdown","id":"455ebc63-1603-40b9-84d9-ed8c0c191723","metadata":{},"outputs":[],"source":["We can concatenate or combine strings by using the addition symbols, and the result is a new string that is a combination of both:\n"]},{"cell_type":"code","id":"e5a5ad8d-5a52-4471-8ce1-c99701a80d21","metadata":{},"outputs":[],"source":["# Concatenate two strings\n\nstatement = name + \" is the best\"\nstatement"]},{"cell_type":"markdown","id":"fa6cd616-461e-4ab2-9385-e050a18cb983","metadata":{},"outputs":[],"source":["To replicate values of a string we simply multiply the string by the number of times we would like to replicate it. In this case, the number is three. The result is a new string, and this new string consists of three copies of the original string:\n"]},{"cell_type":"code","id":"1a07f6b4-6b8c-4b59-bf24-f2b6f2312130","metadata":{},"outputs":[],"source":["# Print the string for 3 times\n\n3 * \"Michael Jackson\""]},{"cell_type":"markdown","id":"3cdf10a3-2bc1-4561-b2cb-62431b720119","metadata":{},"outputs":[],"source":["You can create a new string by setting it to the original variable. Concatenated  with a new string, the result is a new string that changes from Michael Jackson to “Michael Jackson is the best\".\n"]},{"cell_type":"code","id":"25215715-1d9a-4795-9ddf-0b99c3d43404","metadata":{},"outputs":[],"source":["# Concatenate strings\n\nname = \"Michael Jackson\"\nname = name + \" is the best\"\nname"]},{"cell_type":"markdown","id":"cb02b09e-2020-4c4a-a7f5-bf2acce6b200","metadata":{},"outputs":[],"source":["<hr>\n"]},{"cell_type":"markdown","id":"58a07ed7-7a76-46d7-afc9-19af31dff843","metadata":{},"outputs":[],"source":["## Escape Sequences\n"]},{"cell_type":"markdown","id":"ad9a4631-7783-4524-9843-d02229e773f1","metadata":{},"outputs":[],"source":["Back slashes represent the beginning  of escape sequences. Escape sequences represent strings that may be difficult to input. For example, back slash \"n\" represents a new line. The output is given by a new line after the back slash \"n\" is encountered:\n"]},{"cell_type":"code","id":"bdf29ad0-4bfb-4472-90bf-4730edb2c60d","metadata":{},"outputs":[],"source":["# New line escape sequence\n\nprint(\" Michael Jackson \\n is the best\" )"]},{"cell_type":"markdown","id":"bac8b89e-d582-42db-976b-7e37502d197b","metadata":{},"outputs":[],"source":["Similarly, back slash  \"t\" represents a tab:\n"]},{"cell_type":"code","id":"7272fc6f-b208-49cd-bda0-ac3a8848c561","metadata":{},"outputs":[],"source":["# Tab escape sequence\n\nprint(\" Michael Jackson \\t is the best\" )"]},{"cell_type":"markdown","id":"2fe6fd67-3e74-4a83-9e4d-98a82068a7a7","metadata":{},"outputs":[],"source":["If you want to place a back slash in your string, use a double back slash:\n"]},{"cell_type":"code","id":"fbc8ee3f-3f66-4085-b129-33dac3666a07","metadata":{},"outputs":[],"source":["# Include back slash in string\n\nprint(\" Michael Jackson \\\\ is the best\" )"]},{"cell_type":"markdown","id":"54f42287-01ce-4fe6-b7d0-2531d69a71f1","metadata":{},"outputs":[],"source":["We can also place an \"r\" before the string to display the backslash:\n"]},{"cell_type":"code","id":"e2e105d2-96c5-4e0f-be6f-0149e8b1b9d4","metadata":{},"outputs":[],"source":["# r will tell python that string will be display as raw string\n\nprint(r\" Michael Jackson \\ is the best\" )"]},{"cell_type":"markdown","id":"19cfd200-2983-4ffb-8c79-eeeeff201631","metadata":{},"outputs":[],"source":["<hr>\n"]},{"cell_type":"markdown","id":"a6084320-79f3-4ce4-b0ac-106fd5722081","metadata":{},"outputs":[],"source":["## String Manipulation Operations\n"]},{"cell_type":"markdown","id":"71459049-2ae3-4063-ada2-aa104f64f44e","metadata":{},"outputs":[],"source":["There are many string operation methods in Python that can be used to manipulate the data. We are going to use some basic string operations on the data.\n"]},{"cell_type":"markdown","id":"8c8a52a5-99e9-41e5-9149-aefcd341f23e","metadata":{},"outputs":[],"source":["Let's try with the method <code>upper</code>; this method converts lower case characters to upper case characters:\n"]},{"cell_type":"code","id":"066baf9c-4903-49a4-a745-189f7fb838ff","metadata":{},"outputs":[],"source":["# Convert all the characters in string to upper case\n\na = \"Thriller is the sixth studio album\"\nprint(\"before upper:\", a)\nb = a.upper()\nprint(\"After upper:\", b)"]},{"cell_type":"markdown","id":"aabf1f80-3dce-40dd-8fc3-4f25d35832a8","metadata":{},"outputs":[],"source":["The method <code>replace</code> replaces a segment of the string, i.e. a substring  with a new string. We input the part of the string we would like to change. The second argument is what we would like to exchange the segment with, and the result is a new string with the segment changed:\n"]},{"cell_type":"code","id":"99b1ef7d-1f73-4a1c-aa15-9ee1e5d3d5ee","metadata":{},"outputs":[],"source":["# Replace the old substring with the new target substring is the segment has been found in the string\n\na = \"Michael Jackson is the best\"\nb = a.replace('Michael', 'Janet')\nb"]},{"cell_type":"markdown","id":"7cce76c9-3f30-4ddc-a210-f4cfa44c7cd1","metadata":{},"outputs":[],"source":["The method <code>find</code> finds a sub-string. The argument is the substring you would like to find, and the output is the first index of the sequence. We can find the sub-string <code>jack</code> or <code>el<code>.\n"]},{"cell_type":"markdown","id":"4d5e1774-59a7-4d62-8cbf-6722bae69a29","metadata":{},"outputs":[],"source":["<img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%201/images/StringsFind.png\" width=\"600\" align=\"center\">\n"]},{"cell_type":"code","id":"fc1512b3-0534-4d65-a3bb-038eefae436c","metadata":{},"outputs":[],"source":["# Find the substring in the string. Only the index of the first elment of substring in string will be the output\n\nname = \"Michael Jackson\"\nname.find('el')"]},{"cell_type":"code","id":"3bc862a9-f6c1-4ad8-994d-c91fa0ab44e5","metadata":{},"outputs":[],"source":["# Find the substring in the string.\n\nname.find('Jack')"]},{"cell_type":"markdown","id":"9a32c5e1-7964-4614-b49f-3ee5c611b3b2","metadata":{},"outputs":[],"source":["If the  sub-string is not in the string then the output is a negative one. For example, the string 'Jasdfasdasdf' is not a substring:\n"]},{"cell_type":"code","id":"06240c78-7c71-48e1-a9e5-14911729a254","metadata":{},"outputs":[],"source":["# If cannot find the substring in the string\n\nname.find('Jasdfasdasdf')"]},{"cell_type":"markdown","id":"7478b1db-c23e-4686-95b7-c31ebcec5412","metadata":{},"outputs":[],"source":["The method <code>Split</code> splits the string at the specified separator, and returns a list.\n","\n","**Syntax**\n","\n","<code>string.split(separator, maxsplit)</code>\n","\n","**Parameters**\n","- separator (optional): This is the delimiter at which the string will be split. If not provided, the default separator is any whitespace.\n","- maxsplit (optional): This specifies the maximum number of splits to perform. If not provided, there is no limit on the number of splits.\n","\n","**Return Value**:\n","\n","The method returns a list of substrings.\n"]},{"cell_type":"code","id":"fccf664e-2804-4576-966f-7efdcea471e2","metadata":{},"outputs":[],"source":["#Split the substring into list\nname = \"Michael Jackson\"\nsplit_string = (name.split())\nsplit_string"]},{"cell_type":"markdown","id":"d2aeed40-5502-43cc-87dd-b46511439c53","metadata":{},"outputs":[],"source":["<hr>\n"]},{"cell_type":"markdown","id":"2df9322b-9cc2-4fd0-b85e-35bf30dc044e","metadata":{},"outputs":[],"source":["## RegEx\n"]},{"cell_type":"markdown","id":"1a54421d-f225-41fd-b64a-c0556e849606","metadata":{},"outputs":[],"source":["In Python, RegEx (short for Regular Expression) is a tool for matching and handling strings. \n"]},{"cell_type":"markdown","id":"65f9d29a-c539-4135-847c-c08c4a99ba58","metadata":{},"outputs":[],"source":["This RegEx module provides several functions for working with regular expressions, including <code>search, split, findall,</code> and <code>sub</code>. \n"]},{"cell_type":"markdown","id":"35e935d6-a91a-46b9-9d8d-a069c7b78b63","metadata":{},"outputs":[],"source":["Python provides a built-in module called <code>re</code>, which allows you to work with regular expressions. \n","First, import the <code>re</code> module\n"]},{"cell_type":"code","id":"a5b4c506-f3d3-4c6c-87ff-18a5e715d654","metadata":{},"outputs":[],"source":["import re"]},{"cell_type":"markdown","id":"751ef090-f040-42b1-b34c-a0a1146e0dd8","metadata":{},"outputs":[],"source":["The search() function searches for specified patterns within a string. Here is an example that explains how to use the search() function to search for the word \"Jackson\" in the string \"Michael Jackson is the best\".\n"]},{"cell_type":"code","id":"f0787c4f-0f1f-4f5e-b7e2-ad3b52c7c4b3","metadata":{},"outputs":[],"source":["s1 = \"Michael Jackson is the best\"\n\n# Define the pattern to search for\npattern = r\"Jackson\"\n\n# Use the search() function to search for the pattern in the string\nresult = re.search(pattern, s1)\n\n# Check if a match was found\nif result:\n    print(\"Match found!\")\nelse:\n    print(\"Match not found.\")\n"]},{"cell_type":"markdown","id":"7879b44a-4d85-4efd-896c-07a15ad499fe","metadata":{},"outputs":[],"source":["Regular expressions (RegEx) are patterns used to match and manipulate strings of text. There are several special sequences in RegEx that can be used to match specific characters or patterns.\n","\n","| Special Sequence | Meaning                 | \tExample             |\n","| -----------  | ----------------------- | ----------------------|\n","| \\d|Matches any digit character (0-9)|\"123\" matches \"\\d\\d\\d\"|\n","|\\D|Matches any non-digit character|\"hello\" matches \"\\D\\D\\D\\D\\D\"|\n","|\\w|Matches any word character (a-z, A-Z, 0-9, and _)|\"hello_world\" matches \"\\w\\w\\w\\w\\w\\w\\w\\w\\w\\w\\w\"|\n","|\\W|Matches any non-word character|\t\"@#$%\" matches \"\\W\\W\\W\\W\"|\n","|\\s|Matches any whitespace character (space, tab, newline, etc.)|\"hello world\" matches \"\\w\\w\\w\\w\\w\\s\\w\\w\\w\\w\\w\"|\n","|\\S|Matches any non-whitespace character|\"hello_world\" matches \"\\S\\S\\S\\S\\S\\S\\S\\S\\S\"|\n","|\\b|Matches the boundary between a word character and a non-word character|\"cat\" matches \"\\bcat\\b\" in \"The cat sat on the mat\"|\n","|\\B|Matches any position that is not a word boundary|\"cat\" matches \"\\Bcat\\B\" in \"category\" but not in \"The cat sat on the mat\"|\n"]},{"cell_type":"markdown","id":"0a8fa19c-cc75-447a-b45a-348cd4d5e1c0","metadata":{},"outputs":[],"source":["Special Sequence Examples:\n","\n","A simple example of using the <code>\\d</code> special sequence in a regular expression pattern with Python code:\n"]},{"cell_type":"code","id":"080cbf8c-8ee2-41a7-ab71-cbf9269179a7","metadata":{},"outputs":[],"source":["pattern = r\"\\d\\d\\d\\d\\d\\d\\d\\d\\d\\d\"  # Matches any ten consecutive digits\ntext = \"My Phone number is 1234567890\"\nmatch = re.search(pattern, text)\n\nif match:\n    print(\"Phone number found:\", match.group())\nelse:\n    print(\"No match\")"]},{"cell_type":"markdown","id":"58ddccae-947e-4d16-acb5-1e916414f4ff","metadata":{},"outputs":[],"source":["The match.group() method is used in Python's re module to retrieve the part of the string where the regular expression pattern matched. Here's a detailed explanation:\n","\n","**Purpose**\n","- Extract Matched Text: match.group() returns the exact substring that matched the pattern.\n"," \n","**Usage**\n","- When you use functions like re.search() or re.match(), they return a match object if the pattern is found. You can then use match.group() to get the matched text.\n","\n","Here `match.group()` retrieves the substring 1234567890 from the text, which is the part that matched the pattern.\n"]},{"cell_type":"markdown","id":"03d4c2bc-d3ad-4699-b226-3fee3f8c2fec","metadata":{},"outputs":[],"source":["The regular expression pattern is defined as r\"\\d\\d\\d\\d\\d\\d\\d\\d\\d\\d\", which uses the \\d special sequence to match any digit character (0-9), and the \\d sequence is repeated ten times to match ten consecutive digits\n"]},{"cell_type":"markdown","id":"a5fe44c0-9ffb-4e90-a557-e5935624eaae","metadata":{},"outputs":[],"source":["A simple example of using the <code>\\W</code> special sequence in a regular expression pattern with Python code:\n"]},{"cell_type":"code","id":"c8868aee-65c6-4ad4-9942-ec4e153331fc","metadata":{},"outputs":[],"source":["pattern = r\"\\W\"  # Matches any non-word character\ntext = \"Hello, world!\"\nmatches = re.findall(pattern, text)\n\nprint(\"Matches:\", matches)"]},{"cell_type":"markdown","id":"52d5672e-6a4a-45cc-a07b-3a3b2f5ad4e0","metadata":{},"outputs":[],"source":["The regular expression pattern is defined as r\"\\W\", which uses the \\W special sequence to match any character that is not a word character (a-z, A-Z, 0-9, or _). The string we're searching for matches in is \"Hello, world!\".\n"]},{"cell_type":"markdown","id":"4631fc14-6604-4824-acaf-b7b8c30b1c36","metadata":{},"outputs":[],"source":["The <code>findall()</code> function finds all occurrences of a specified pattern within a string.\n"]},{"cell_type":"code","id":"cc006eee-d6a5-47b1-8a57-9bc38f842a2f","metadata":{},"outputs":[],"source":["s2 = \"Michael Jackson was a singer and known as the 'King of Pop'\"\n\n\n# Use the findall() function to find all occurrences of the \"as\" in the string\nresult = re.findall(\"as\", s2)\n\n# Print out the list of matched words\nprint(result)\n"]},{"cell_type":"markdown","id":"50ff3a6c-4bad-4d59-bab2-604539143df3","metadata":{},"outputs":[],"source":["A regular expression's <code>split()</code> function splits a string into an array of substrings based on a specified pattern.\n"]},{"cell_type":"code","id":"63eee120-f14f-492a-a59c-a60605c4ef4e","metadata":{},"outputs":[],"source":["# Use the split function to split the string by the \"\\s\"\nsplit_array = re.split(r\"\\s\", s2)\n\n# The split_array contains all the substrings, split by whitespace characters\nprint(split_array)"]},{"cell_type":"markdown","id":"9252b6db-091c-4339-a01e-9cb5d2531b30","metadata":{},"outputs":[],"source":["Here's a detailed explanation: \n","\n","<code>re.split(\"\\s\", s2)</code>:\n","\n","**re.split**: This function splits a string by the occurrences of a pattern.\n","- **r\"\\s\"**: This is a regular expression pattern that matches any whitespace character (spaces, tabs, newlines, etc.).\n","- **s2**: This is the string that you want to split.\n"]},{"cell_type":"markdown","id":"c41422ea-63e3-4023-9f4c-f273da1fb01a","metadata":{},"outputs":[],"source":["The <code>sub</code> function of a regular expression in Python is used to replace all occurrences of a pattern in a string with a specified replacement.\n"]},{"cell_type":"code","id":"2b02a3c9-464d-4ece-9d3d-84170663c7c0","metadata":{},"outputs":[],"source":["# Define the regular expression pattern to search for\npattern = r\"King of Pop\"\n\n# Define the replacement string\nreplacement = \"legend\"\n\n# Use the sub function to replace the pattern with the replacement string\nnew_string = re.sub(pattern, replacement, s2, flags=re.IGNORECASE)\n\n# The new_string contains the original string with the pattern replaced by the replacement string\nprint(new_string) "]},{"cell_type":"markdown","id":"0ed53faf-5c07-4fb7-8e3b-910e6b4b293d","metadata":{},"outputs":[],"source":["<hr>\n"]},{"cell_type":"markdown","id":"125f15fa-4f08-454f-896b-f307d95bfe4d","metadata":{},"outputs":[],"source":["<h2 id=\"quiz\">Quiz on Strings</h2>\n"]},{"cell_type":"markdown","id":"8aabc9e7-5724-40d6-bfe9-ba9e5e859b02","metadata":{},"outputs":[],"source":["What is the value of the variable <code>a</code> after the following code is executed?\n"]},{"cell_type":"code","id":"56ea4a45-947f-416a-a7a7-f1fbfb3cbedf","metadata":{},"outputs":[],"source":["# Write your code below and press Shift+Enter to execute \n\na = \"1\""]},{"cell_type":"markdown","id":"fc4aff5c-214a-4f2c-a5e0-e3067dd81819","metadata":{},"outputs":[],"source":["<details><summary>Click here for the solution</summary>\n","\n","```python\n","\"1\"\n","\n","```\n","\n","</details>\n"]},{"cell_type":"markdown","id":"8ff5ea40-1271-47f7-9f73-8f4ae5a25e0a","metadata":{},"outputs":[],"source":["What is the value of the variable <code>b</code> after the following code is executed?\n"]},{"cell_type":"code","id":"e3969441-29f5-43f2-829e-d9920e3ccc35","metadata":{},"outputs":[],"source":["# Write your code below and press Shift+Enter to execute\n\nb = \"2\""]},{"cell_type":"markdown","id":"8133b4dd-b06b-48ab-9760-359c54573d52","metadata":{},"outputs":[],"source":["<details><summary>Click here for the solution</summary>\n","\n","```python\n","\"2\"\n","\n","```\n","\n","</details>\n"]},{"cell_type":"markdown","id":"6886ac8e-5b89-4074-b94a-8cebb3ce1bc1","metadata":{},"outputs":[],"source":["What is the value of the variable <code>c</code> after the following code is executed?\n"]},{"cell_type":"code","id":"8a417d26-515b-47f6-9901-45ab8c8ac700","metadata":{},"outputs":[],"source":["# Write your code below and press Shift+Enter to execute \n\nc = a + b"]},{"cell_type":"markdown","id":"38ddcdaf-4b0e-4a0f-941e-cc91b234c777","metadata":{},"outputs":[],"source":["<details><summary>Click here for the solution</summary>\n","\n","```python\n","\"12\"\n","\n","```\n","\n","</details>\n"]},{"cell_type":"markdown","id":"7c98e0ee-3ac8-47c8-b9a0-9c30092cb6df","metadata":{},"outputs":[],"source":["<hr>\n"]},{"cell_type":"markdown","id":"01855e16-fe4e-4a8d-a123-7f65725f081f","metadata":{},"outputs":[],"source":["Consider the variable <code>d</code> use slicing to print out the first three elements:\n"]},{"cell_type":"code","id":"d66596e2-5562-43db-9645-1f2237291836","metadata":{},"outputs":[],"source":["# Write your code below and press Shift+Enter to execute\n\nd = \"ABCDEFG\""]},{"cell_type":"markdown","id":"33052bbe-33c4-433f-b208-561ef9654c8c","metadata":{},"outputs":[],"source":["<details><summary>Click here for the solution</summary>\n","\n","```python\n","print(d[:3]) \n","\n","# or \n","\n","print(d[0:3])\n","\n","```\n","\n","</details>\n"]},{"cell_type":"markdown","id":"bd57302e-858f-428f-ba3a-5bc81e0c5ffb","metadata":{},"outputs":[],"source":["<hr>\n"]},{"cell_type":"markdown","id":"db472015-306e-42c4-970a-4ce827fe61c0","metadata":{},"outputs":[],"source":["Use a stride value of 2 to print out every second character of the string <code>e</code>:\n"]},{"cell_type":"code","id":"309d9592-9c56-41ab-89f7-8c977d4424e2","metadata":{},"outputs":[],"source":["# Write your code below and press Shift+Enter to execute\n\ne = 'clocrkr1e1c1t'"]},{"cell_type":"markdown","id":"37fd6cf3-38b2-4c58-b860-1c3216296ee7","metadata":{},"outputs":[],"source":["<details><summary>Click here for the solution</summary>\n","\n","```python\n","print(e[::2])\n","\n","```\n","\n","</details>\n"]},{"cell_type":"markdown","id":"45a2c50a-850b-4825-a59e-f9e3a736ae0e","metadata":{},"outputs":[],"source":["<hr>\n"]},{"cell_type":"markdown","id":"9317d19c-cb12-4060-9402-3b8805a0bd21","metadata":{},"outputs":[],"source":["Print out a backslash:\n"]},{"cell_type":"code","id":"95a4915a-5445-4cac-93a0-440585648342","metadata":{},"outputs":[],"source":["# Write your code below and press Shift+Enter to execute\n"]},{"cell_type":"markdown","id":"265b868b-87c6-4a50-87e1-5ae5918a92c2","metadata":{},"outputs":[],"source":["<details><summary>Click here for the solution</summary>\n","\n","```python\n","print(\"\\\\\\\\\")\n","\n","or\n","\n","\n","\n","```\n","\n","</details>\n"]},{"cell_type":"markdown","id":"44f2de38-e527-4e90-8966-65d266a59ae9","metadata":{},"outputs":[],"source":["<hr>\n"]},{"cell_type":"markdown","id":"9c19b0f5-f902-4b7b-93e9-408219a0478c","metadata":{},"outputs":[],"source":["Convert the variable <code>f</code> to uppercase:\n"]},{"cell_type":"code","id":"6eec1ab1-3922-4dcf-9240-403161f62a98","metadata":{},"outputs":[],"source":["# Write your code below and press Shift+Enter to execute\n\nf = \"You are wrong\""]},{"cell_type":"markdown","id":"2f3d393c-3f75-464d-9755-6380cb2d74df","metadata":{},"outputs":[],"source":["<details><summary>Click here for the solution</summary>\n","\n","```python\n","f.upper()\n","\n","```\n","\n","</details>\n"]},{"cell_type":"markdown","id":"0114c4cd-f378-4e04-a597-1756e39c5439","metadata":{},"outputs":[],"source":["Convert the variable <code>f2</code> to lowercase:\n"]},{"cell_type":"code","id":"4876c819-3889-4480-8679-a19085a013fe","metadata":{},"outputs":[],"source":["# Write your code below and press Shift+Enter to execute\nf2=\"YOU ARE RIGHT\""]},{"cell_type":"markdown","id":"f6fa2fe3-9ab5-4dbe-9067-0f7bd925bff3","metadata":{},"outputs":[],"source":["<details><summary>Click here for the solution</summary>\n","\n","```python\n","f2.lower()\n","\n","```\n","\n","</details>\n"]},{"cell_type":"markdown","id":"b03ab10b-55d9-49f8-b84e-fb2715306bbc","metadata":{},"outputs":[],"source":["<hr>\n"]},{"cell_type":"markdown","id":"d232adae-417f-476f-b294-d239f93f17c4","metadata":{},"outputs":[],"source":["Consider the variable <code>g</code>, and find the first index of the sub-string <code>snow</code>:\n"]},{"cell_type":"code","id":"01f70105-639b-4fb5-809c-163fc9d24941","metadata":{},"outputs":[],"source":["# Write your code below and press Shift+Enter to execute\n\ng = \"Mary had a little lamb Little lamb, little lamb Mary had a little lamb \\\nIts fleece was white as snow And everywhere that Mary went Mary went, Mary went \\\nEverywhere that Mary went The lamb was sure to go\""]},{"cell_type":"markdown","id":"0785b4ca-ea0c-457f-a230-09d75562afa6","metadata":{},"outputs":[],"source":["<details><summary>Click here for the solution</summary>\n","\n","```python\n","g.find(\"snow\")\n","\n","```\n","\n","</details>\n"]},{"cell_type":"markdown","id":"87d87f0c-9ff1-4425-acb5-23079e22983a","metadata":{},"outputs":[],"source":["In the variable <code>g</code>, replace the sub-string <code>Mary</code> with <code>Bob</code>:\n"]},{"cell_type":"code","id":"3064ef1f-3fa8-4c87-b43a-f9a66a6f4997","metadata":{},"outputs":[],"source":["# Write your code below and press Shift+Enter to execute\n"]},{"cell_type":"markdown","id":"8d6abdde-4a24-4c51-abd0-94c37dc8f777","metadata":{},"outputs":[],"source":["<details><summary>Click here for the solution</summary>\n","\n","```python\n","g.replace(\"Mary\", \"Bob\")\n","\n","```\n","\n","</details>\n"]},{"cell_type":"markdown","id":"d8226296-a842-4986-8ca7-9131d21400ab","metadata":{},"outputs":[],"source":["In the variable <code>g</code>, replace the sub-string <code>,</code> with <code>.</code>:\n"]},{"cell_type":"code","id":"710f1197-26bb-4ba0-a066-e96ac11b6e1b","metadata":{},"outputs":[],"source":["# Write your code below and press Shift+Enter to execute"]},{"cell_type":"markdown","id":"3050ff8f-d883-4174-8ad3-38c1f46e8984","metadata":{},"outputs":[],"source":["<details><summary>Click here for the solution</summary>\n","\n","```python\n","g.replace(',','.')\n","\n","```\n","\n","</details>\n"]},{"cell_type":"markdown","id":"ba264693-f553-4502-bd54-9a28a868937f","metadata":{},"outputs":[],"source":["In the variable <code>g</code>, split the substring to list:\n"]},{"cell_type":"code","id":"65df8127-9e5a-474e-8937-6d8b7dae8c42","metadata":{},"outputs":[],"source":["# Write your code below and press Shift+Enter to execute"]},{"cell_type":"markdown","id":"0910d112-28ae-4377-ae7e-f1627716a6cf","metadata":{},"outputs":[],"source":["<details><summary>Click here for the solution</summary>\n","\n","```python\n","g.split()\n","\n","```\n","\n","</details>\n"]},{"cell_type":"markdown","id":"cda02d53-0334-4460-938e-9fc800065629","metadata":{},"outputs":[],"source":["In the string <code>s3</code>, find whether the digit is present or not using the <code>\\d</code> and <code>search() </code>function:\n"]},{"cell_type":"code","id":"3ab53b01-af70-473d-824d-8efb386f7f4e","metadata":{},"outputs":[],"source":["s3 = \"House number- 1105\"\n# Write your code below and press Shift+Enter to execute"]},{"cell_type":"markdown","id":"6e7d4138-1e5d-4e98-a67b-93ed11189973","metadata":{},"outputs":[],"source":["<details><summary>Click here for the solution</summary>\n","\n","```python\n","# Use the search() function to search for the \"\\d\" in the string\n","result = re.search(r\"\\d\", s3)\n","\n","# Check if a match was found\n","if result:\n","    print(\"Digit found\")\n","else:\n","    print(\"Digit not found.\")\n","```\n","\n","</details>\n"]},{"cell_type":"markdown","id":"4889ac57-fa38-438e-bcd7-d47b540d82e4","metadata":{},"outputs":[],"source":["In the string <code>str1</code>, replace the sub-string <code>fox</code> with <code>bear</code> using <code>sub() </code>function:\n"]},{"cell_type":"code","id":"f2eab1d4-41a5-4e67-bbbd-0ea91560749c","metadata":{},"outputs":[],"source":["str1= \"The quick brown fox jumps over the lazy dog.\"\n\n# Write your code below and press Shift+Enter to execute\n"]},{"cell_type":"markdown","id":"c8754f0e-ab0f-47cd-984b-1e66297a1b4d","metadata":{},"outputs":[],"source":["<details><summary>Click here for the solution</summary>\n","\n","```python\n","# Use re.sub() to replace \"fox\" with \"bear\"\n","new_str1 = re.sub(r\"fox\", \"bear\", str1)\n","\n","print(new_str1)\n","```\n","\n","</details>\n"]},{"cell_type":"markdown","id":"cfa38a8e-7f32-4947-9a62-8fbc4a67f002","metadata":{},"outputs":[],"source":["In the string <code>str2</code> find all the occurrences of <code>woo</code> using <code>findall()</code> function:\n"]},{"cell_type":"code","id":"563ec1c4-1fd5-4952-98b9-144dd26b7c54","metadata":{},"outputs":[],"source":["str2= \"How much wood would a woodchuck chuck, if a woodchuck could chuck wood?\"\n\n# Write your code below and press Shift+Enter to execute\n"]},{"cell_type":"markdown","id":"0894ee1a-abb0-4253-8fe7-357d68c713c5","metadata":{},"outputs":[],"source":["<details><summary>Click here for the solution</summary>\n","\n","```python\n","# Use re.findall() to find all occurrences of \"woo\"\n","matches = re.findall(r\"woo\", str2)\n","\n","print(matches)\n","```\n","\n","</details>\n"]},{"cell_type":"markdown","id":"c5a6bc3e-fd0b-49e8-8a45-67448029a714","metadata":{},"outputs":[],"source":["<hr>\n","<h2>The last exercise!</h2>\n","<p>Congratulations, you have completed your first lesson and hands-on lab in Python.\n","<hr>\n"]},{"cell_type":"markdown","id":"ba23caa1-7c4d-4209-a530-7f1053075472","metadata":{},"outputs":[],"source":["## Author\n","\n","<a href=\"https://www.linkedin.com/in/joseph-s-50398b136/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkPY0101ENSkillsNetwork19487395-2021-01-01\" target=\"_blank\">Joseph Santarcangelo</a>\n","\n","<img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/SNIBMfooter.png\" alt=\"\" width=\"\" height=\"\">\n"]}],"metadata":{"kernelspec":{"name":"python","display_name":"Python (Pyodide)","language":"python"},"language_info":{"codemirror_mode":{"name":"python","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.8"},"prev_pub_hash":"a84fd28f95ce4a99db45375cf8f3d988febb032607fa325f629d51545952e082"},"nbformat":4,"nbformat_minor":4}