{"id":5976,"date":"2022-04-30T08:41:25","date_gmt":"2022-04-30T06:41:25","guid":{"rendered":"http:\/\/miro.borodziuk.eu\/?p=5976"},"modified":"2026-01-23T16:32:34","modified_gmt":"2026-01-23T15:32:34","slug":"strings-in-python","status":"publish","type":"post","link":"http:\/\/miro.borodziuk.eu\/index.php\/2022\/04\/30\/strings-in-python\/","title":{"rendered":"Strings in Python"},"content":{"rendered":"<p>1. Python strings are <strong>immutable<\/strong> sequences and can be indexed, sliced, and iterated like any other sequence, as well as being subject to the in and not in operators. There are two kinds of strings in Python:<\/p>\n<p><!--more--><\/p>\n<ul>\n<li><strong>one-line strings<\/strong>, which cannot cross line boundaries \u2013 we denote them using either apostrophes (<strong><code>'string'<\/code><\/strong>) or quotes (<strong><code>\"string\"<\/code><\/strong>)<\/li>\n<li><strong>multi-line strings<\/strong>, which occupy more than one line of source code, delimited by trigraphs:<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true\">'''\r\nstring\r\n'''<\/pre>\n<p>or<\/p>\n<pre class=\"lang:default decode:true\">\"\"\"\r\nstring\r\n\"\"\"<\/pre>\n<p>&nbsp;<\/p>\n<p>2. The length of a string is determined by the<strong><code> len()<\/code><\/strong> function. The escape character (<strong><code>\\<\/code><\/strong>) is not counted. For example:<\/p>\n<pre class=\"lang:default decode:true \">print(len(\"\\n\\n\"))<\/pre>\n<p><code>2<\/code><\/p>\n<pre class=\"lang:default decode:true\">x=\"\\\\\\\\\"\r\nprint(len(x))\r\n<\/pre>\n<p><code>2<\/code><\/p>\n<pre class=\"lang:default decode:true\">x=\"\\\\\\\"\r\nprint(len(x))\r\n<\/pre>\n<p><code>\u00a0x=\"\\\\\\\"<\/code><br \/>\n<code>\u00a0 \u00a0 \u00a0 ^<\/code><br \/>\n<code>SyntaxError: unterminated string literal (detected at line 1)<\/code><\/p>\n<p>\\ escape only one character.<\/p>\n<p>&nbsp;<\/p>\n<p>3. Strings can be concatenated using the<strong><code> +<\/code><\/strong> operator, and replicated using the <strong><code>*<\/code><\/strong> operator. For example:<\/p>\n<pre class=\"lang:default decode:true\">asterisk = '*'\r\nplus = \"+\"\r\ndecoration = (asterisk + plus) * 4 + asterisk\r\nprint(decoration)<\/pre>\n<p>outputs *+*+*+*+*.<\/p>\n<p>&nbsp;<\/p>\n<p>4. The pair of functions <strong><code>chr()<\/code> <\/strong>and <strong><code>ord()<\/code><\/strong> can be used to create a character using its codepoint, and to determine a codepoint corresponding to a character. Both of the following expressions are always true:<\/p>\n<pre class=\"lang:default decode:true \">chr(ord(character)) == character\r\nord(chr(codepoint)) == codepoint<\/pre>\n<p>&nbsp;<\/p>\n<p>5. Some other functions that can be applied to strings are:<\/p>\n<p><code>list()<\/code> \u2013 create a list consisting of all the string&#8217;s characters;<br \/>\n<code>max()<\/code> \u2013 finds the character with the maximal codepoint;<br \/>\n<code>min()<\/code> \u2013 finds the character with the minimal codepoint.<\/p>\n<p>&nbsp;<\/p>\n<p>6. The method named <code><strong>index()<\/strong><\/code> finds the index of a given substring inside the string and raises an exception if the value is not found.<\/p>\n<p>The syntax is as follows :<br \/>\n<code>string.index(value, start, end)<\/code>\u00a0 where:<br \/>\n&#8211; value [required] : the string\/character to search for<br \/>\n&#8211; start [optional] : the index to start the search (default is 0)<br \/>\n&#8211; end [optional] : the index to end the search (default is the end of the string) &#8211; note that this index is excluded from the search.<\/p>\n<pre class=\"lang:default decode:true \">    my_str = 'Luke !!\\n'\r\n    z = my_str.index('n')\r\n    print(z)                # ValueError Exception\r\n     \r\n    x = my_str.index('L')\r\n    print(x)                # 0\r\n     \r\n    y = my_str.index('!',4)\r\n    print(y)                # 5\r\n     \r\n    w = my_str.index('!',1,5)\r\n    print(w)                # ValueError Exception<\/pre>\n<p>In the above question,<code> my_str.index('n')<\/code> will return the index of the first occurrence of the letter &#8220;n&#8221; in the string<code> my_str<\/code>, searching between the character at position 0 and the last character of the string (i.e. the whole string). In the string &#8216;Luke !!\\n&#8217; , <code>'\\n'<\/code> is actually the code for a new line (note that escape character &#8216;\\&#8217;); this is not representing the character &#8216;n&#8217;. So character<code> 'n'<\/code> is NOT in the string &#8216;Luke !!\\n&#8217; and my_str.index(&#8216;n&#8217;) will raise an exception.<\/p>\n<p>&nbsp;<\/p>\n<p>7. Some of the methods offered by strings are:<\/p>\n<ul>\n<li><code><strong>capitalize()<\/strong><\/code> \u2013 changes all string letters to capitals;<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true \"># Demonstrating the capitalize() method:\r\nprint('aBcD'.capitalize())\r\nprint(\"Alpha\".capitalize())\r\nprint('ALPHA'.capitalize())\r\nprint(' Alpha'.capitalize())\r\nprint('123'.capitalize())\r\nprint(\"\u03b1\u03b2\u03b3\u03b4\".capitalize())<\/pre>\n<p><code>Abcd<\/code><br \/>\n<code>Alpha<\/code><br \/>\n<code>Alpha<\/code><br \/>\n<code>alpha<\/code><br \/>\n<code>123<\/code><br \/>\n<code>\u0391\u03b2\u03b3\u03b4<\/code><\/p>\n<ul>\n<li><strong><code>center()<\/code><\/strong> \u2013 centers the string inside the field of a known length;<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true \"># Demonstrating the center() method:\r\nprint('[' + 'alpha'.center(10) + ']')\r\nprint('[' + 'Beta'.center(2) + ']')\r\nprint('[' + 'Beta'.center(4) + ']')\r\nprint('[' + 'Beta'.center(6) + ']')<\/pre>\n<p><code>[\u00a0 \u00a0alpha\u00a0 \u00a0]<\/code><br \/>\n<code>[Beta]<\/code><br \/>\n<code>[Beta]<\/code><br \/>\n<code>[ Beta ]<\/code><\/p>\n<p>The two-parameter variant of <code>center()<\/code> makes use of the character from the second argument, instead of a space. Analyze the example below:<\/p>\n<pre class=\"lang:default decode:true \">print('[' + 'gamma'.center(20, '*') + ']')<\/pre>\n<p><code class=\"codep \">[*******gamma********]<\/code><\/p>\n<p>&nbsp;<\/p>\n<ul>\n<li><code><strong>count()<\/strong><\/code> \u2013 counts the occurrences of a given character;<\/li>\n<\/ul>\n<p><code><\/code><\/p>\n<ul>\n<li><code><strong>join()<\/strong><\/code> \u2013 joins all items of a tuple\/list into one string;<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true \"># Demonstrating the join() method:\r\nprint(\",\".join([\"omicron\", \"pi\", \"rho\"]))<\/pre>\n<p><code>omicron,pi,rho<\/code><\/p>\n<pre class=\"lang:default decode:true \">myTuple = (\"John\", \"Peter\", \"Vicky\")\r\nx = \"#\".join(myTuple)\r\nprint(x)\r\n<\/pre>\n<p><code>John#Peter#Vicky<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><code><strong>lower()<\/strong><\/code> \u2013 converts all the string&#8217;s letters into lower-case letters;<\/p>\n<pre class=\"lang:default decode:true \"># Demonstrating the lower() method:\r\nprint(\"SiGmA=60\".lower())<\/pre>\n<p><code>sigma=60<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><strong><code>lstrip()<\/code><\/strong> \u2013 removes the white characters from the beginning of the string;<\/p>\n<pre class=\"lang:default decode:true \"># Demonstrating the lstrip() method:\r\nprint(\"[\" + \" tau \".lstrip() + \"]\")<\/pre>\n<p><code>[tau ]<\/code><\/p>\n<p>The one-parameter<strong><code> lstrip()<\/code> <\/strong>method does the same as its parameterless version, but removes all characters enlisted in its argument (a string), not just whitespaces:<\/p>\n<pre class=\"lang:default decode:true \">print(\"www.cisco.com\".lstrip(\"w.\"))<\/pre>\n<p><code>cisco.com<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><strong><code>rstrip()<\/code><\/strong> \u2013 removes the trailing white spaces from the end of the string;<\/p>\n<p>do nearly the same as lstrips, but affect the opposite side of the string.<\/p>\n<pre class=\"lang:default decode:true \"># Demonstrating the rstrip() method:\r\nprint(\"[\" + \" upsilon \".rstrip() + \"]\")\r\nprint(\"cisco.com\".rstrip(\".com\"))<\/pre>\n<p><code>[ upsilon]<\/code><\/p>\n<p><code>cis<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><code><strong>strip()<\/strong><\/code> \u2013 removes the leading and trailing white spaces;<\/p>\n<p>combines the effects caused by <code>rstrip()<\/code> and <code>lstrip()<\/code> &#8211; it makes a new string lacking all the leading and trailing whitespaces.<\/p>\n<pre class=\"lang:default decode:true \"># Demonstrating the strip() method:\r\nprint(\"[\" + \"   aleph   \".strip() + \"]\")<\/pre>\n<p><code>[aleph]<\/code><\/p>\n<pre class=\"lang:default decode:true \">txt = \"     banana     \"\r\nx = txt.strip()\r\nprint(\"of all fruits\", x, \"is my favorite\")\r\n<\/pre>\n<p><code>of all fruits banana is my favorite<\/code><\/p>\n<pre class=\"lang:default decode:true \">txt = \",,,,,rrttgg.....banana....rrr\"\r\nx = txt.strip(\",.grt\")\r\nprint(x)\r\n<\/pre>\n<p><code>banana<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><code><strong>split()<\/strong> <\/code>\u2013 splits the string into a substring using a given delimiter;<\/p>\n<pre class=\"lang:default decode:true\"># Demonstrating the split() method:\r\nprint(\"phi       chi\\npsi\".split())<\/pre>\n<p><code>['phi', 'chi', 'psi']<\/code><\/p>\n<pre class=\"lang:default decode:true \">txt = \"hello, my name is Peter, I am 26 years old\"\r\nx = txt.split(\", \")\r\nprint(x)\r\n<\/pre>\n<p><code>['hello', 'my name is Peter', 'I am 26 years old']<\/code><\/p>\n<p>Note: the reverse operation can be performed by the<code> join()<\/code> method.<\/p>\n<p>&nbsp;<\/p>\n<p><strong><code>replace()<\/code><\/strong> \u2013 replaces a given substring with another;<\/p>\n<pre class=\"lang:default decode:true \"># Demonstrating the replace() method:\r\nprint(\"www.netacad.com\".replace(\"netacad.com\", \"pythoninstitute.org\"))\r\nprint(\"This is it!\".replace(\"is\", \"are\"))\r\nprint(\"Apple juice\".replace(\"juice\", \"\"))<\/pre>\n<p><code>www.pythoninstitute.org<\/code><br \/>\n<code>Thare are it!<\/code><br \/>\n<code>Apple<\/code><\/p>\n<p>The three-parameter replace() variant uses the third argument (a number) to limit the number of replacements.<\/p>\n<pre class=\"lang:default decode:true \">txt = \"one one was a race horse, two two was one too.\"\r\nx = txt.replace(\"one\", \"three\", 2)\r\nprint(x)\r\n<\/pre>\n<p><code>three three was a race horse, two two was one too.<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><strong><code>find()<\/code><\/strong> &#8211; it looks for a substring and returns the index of first occurrence of this substring. For an argument containing a non-existent substring (it returns -1 then)<\/p>\n<pre class=\"lang:default decode:true \"># Demonstrating the find() method:\r\nprint(\"Eta\".find(\"ta\"))\r\nprint(\"Eta\".find(\"mma\"))<\/pre>\n<p>1<br \/>\n-1<\/p>\n<p>&nbsp;<\/p>\n<p><strong><code>rfind()<\/code><\/strong> \u2013 finds a substring starting from the end of the string; <strong><code>string.rfind(value, start, end)\u00a0<\/code><\/strong><\/p>\n<pre class=\"lang:default decode:true \"># Demonstrating the rfind() method:\r\nprint(\"tau tau tau\".rfind(\"ta\"))\r\nprint(\"tau tau tau\".rfind(\"ta\", 9))\r\nprint(\"tau tau tau\".rfind(\"ta\", 3, 9))<\/pre>\n<p><code>8<\/code><br \/>\n<code>-1<\/code><br \/>\n<code>4<\/code><\/p>\n<pre class=\"lang:default decode:true \">txt = \"Mi casa, su casa.\"\r\nx = txt.rfind(\"casa\")\r\nprint(x)\r\n<\/pre>\n<p><code>12<\/code><\/p>\n<pre class=\"lang:default decode:true\">txt = \"Hello, welcome to my world.\"\r\nx = txt.rfind(\"e\", 5, 10)\r\nprint(x)<\/pre>\n<p><code>8<\/code><code><\/code><\/p>\n<p>&nbsp;<\/p>\n<p><strong><code>swapcase()<\/code> <\/strong>\u2013 swaps the letters&#8217; cases (lower to upper and vice versa)<\/p>\n<pre class=\"lang:default decode:true \"># Demonstrating the swapcase() method:\r\nprint(\"I know that I know nothing.\".swapcase())<\/pre>\n<p><code>i KNOW THAT i KNOW NOTHING.<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><code><strong>title()<\/strong><\/code> \u2013 makes the first letter in each word upper-case;<\/p>\n<pre class=\"lang:default decode:true \"># Demonstrating the title() method:\r\nprint(\"I know that I know nothing. Part 1.\".title())<\/pre>\n<p><code>I Know That I Know Nothing. Part 1.<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><code><strong>upper()<\/strong><\/code> \u2013 converts all the string&#8217;s letter into upper-case letters.<\/p>\n<pre class=\"lang:default decode:true \"># Demonstrating the upper() method:\r\nprint(\"I know that I know nothing. Part 2.\".upper())<\/pre>\n<p><code>I KNOW THAT I KNOW NOTHING. PART 2.<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>2. String content can be determined using the following methods (all of them return Boolean values):<\/p>\n<p><strong><code>endswith()<\/code><\/strong> \u2013 does the string end with a given substring?<\/p>\n<pre class=\"lang:default decode:true \"># Demonstrating the endswith() method:\r\nif \"epsilon\".endswith(\"on\"):\r\n    print(\"yes\")\r\nelse:\r\n    print(\"no\")\r\n\r\nt = \"zeta\"\r\nprint(t.endswith(\"a\"))\r\nprint(t.endswith(\"A\"))\r\nprint(t.endswith(\"et\"))\r\nprint(t.endswith(\"eta\"))\r\n<\/pre>\n<p><code>yes<\/code><br \/>\n<code>True<\/code><br \/>\n<code>False<\/code><br \/>\n<code>False<\/code><br \/>\n<code>True<\/code><\/p>\n<p><code><strong>startswith()<\/strong><\/code> \u2013 does the string begin with a given substring?<\/p>\n<p>The <code>startswith()<\/code> method is a mirror reflection of<code> endswith()<\/code> &#8211; it checks if a given string starts with the specified substring.<\/p>\n<pre class=\"lang:default decode:true \"># Demonstrating the startswith() method:\r\nprint(\"omega\".startswith(\"meg\"))\r\nprint(\"omega\".startswith(\"om\"))\r\n\r\n<\/pre>\n<p><code>False<\/code><br \/>\n<code>True<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><code><strong>isalnum()<\/strong><\/code> \u2013 does the string consist only of letters and digits?<\/p>\n<pre class=\"lang:default decode:true \"># Demonstrating the isalnum() method:\r\nprint('lambda30'.isalnum())\r\nprint('lambda'.isalnum())\r\nprint('30'.isalnum())\r\nprint('@'.isalnum())\r\nprint('lambda_30'.isalnum())\r\nprint(''.isalnum())\r\n<\/pre>\n<p><code>True<\/code><br \/>\n<code>True<\/code><br \/>\n<code>True<\/code><br \/>\n<code>False<\/code><br \/>\n<code>False<\/code><br \/>\n<code>False<\/code><\/p>\n<pre class=\"lang:default decode:true \">t = 'Six lambdas'\r\nprint(t.isalnum())\r\n\r\nt = '\u0391\u03b2\u0393\u03b4'\r\nprint(t.isalnum())\r\n\r\nt = '20E1'\r\nprint(t.isalnum())\r\n<\/pre>\n<p><code>False<\/code> (the cause of the first result is a space &#8211; it&#8217;s neither a digit nor a letter.)<br \/>\n<code>True<\/code><br \/>\n<code>True<\/code><\/p>\n<p><strong><code>isalpha()<\/code><\/strong> \u2013 does the string consist only of letters?<\/p>\n<pre class=\"lang:default decode:true \"># Example 1: Demonstrating the isapha() method:\r\nprint(\"Moooo\".isalpha())\r\nprint('Mu40'.isalpha())<\/pre>\n<p><code>True<\/code><br \/>\n<code>False<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><strong><code>isdigit()<\/code> <\/strong>&#8211; looks at digits only &#8211; anything else produces False as the result.<\/p>\n<pre class=\"lang:default decode:true\"># Example 2: Demonstrating the isdigit() method:\r\nprint('2018'.isdigit())\r\nprint(\"Year2019\".isdigit())<\/pre>\n<p><code>True<\/code><br \/>\n<code>False<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><strong><code>islower()<\/code><\/strong> \u2013 does the string consists only of lower-case letters?<\/p>\n<pre class=\"lang:default decode:true\"># Demonstrating the islower() method:\r\nprint(\"Moooo\".islower())\r\nprint('moooo'.islower())<\/pre>\n<p><code>False<\/code><br \/>\n<code>True<\/code><\/p>\n<p><code><strong>isupper()<\/strong><\/code> \u2013 does the string consists only of upper-case letters?<\/p>\n<pre class=\"lang:default decode:true\"># Demonstrating the isupper() method:\r\nprint(\"Moooo\".isupper())\r\nprint('moooo'.isupper())\r\nprint('MOOOO'.isupper())<\/pre>\n<p><code>False<\/code><br \/>\n<code>False<\/code><br \/>\n<code>True<\/code><\/p>\n<p><strong><code>isspace()<\/code> <\/strong>\u2013 does the string consists only of white spaces?<\/p>\n<pre class=\"lang:default decode:true \"># Example 2: Demonstrating the isspace() method:\r\nprint(' \\n '.isspace())\r\nprint(\" \".isspace())\r\nprint(\"mooo mooo mooo\".isspace())<\/pre>\n<p><code>True<\/code><br \/>\n<code>True<\/code><br \/>\n<code>False<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 1<\/em><\/p>\n<p>What is the length of the following string assuming there is no whitespaces between the quotes?<\/p>\n<pre class=\"lang:default decode:true \">\"\"\"\r\n\"\"\"<\/pre>\n<p>&nbsp;<\/p>\n<p><code>1<\/code><\/p>\n<p><em>Exercise 2<\/em><\/p>\n<p>What is the expected output of the following code?<\/p>\n<pre class=\"lang:default decode:true \">s = 'yesteryears'\r\nthe_list = list(s)\r\nprint(the_list[3:6])<\/pre>\n<p>&nbsp;<\/p>\n<p><code>['t', 'e', 'r']<\/code><\/p>\n<p><em>Exercise 3<\/em><\/p>\n<p>What is the expected output of the following code?<\/p>\n<pre class=\"lang:default decode:true \">for ch in \"abc\":\r\n  print(chr(ord(ch) + 1), end='')<\/pre>\n<p>&nbsp;<\/p>\n<p><code>bcd<\/code><\/p>\n<p><em>Exercise 4<\/em><\/p>\n<p>What is the expected output of the following code?<\/p>\n<pre class=\"lang:default decode:true \">for ch in \"abc123XYX\":\r\n  if ch.isupper():\r\n    print(ch.lower(), end='')\r\n  elif ch.islower():\r\n    print(ch.upper(), end='')\r\n  else:\r\n    print(ch, end='')<\/pre>\n<p>&nbsp;<\/p>\n<p><code>ABC123xyx<\/code><\/p>\n<p><em>Exercise 5<\/em><\/p>\n<p>What is the expected output of the following code?<\/p>\n<pre class=\"lang:default decode:true \">s1 = 'Where are the snows of yesteryear?'\r\ns2 = s1.split()\r\nprint(s2[-2])<\/pre>\n<p>&nbsp;<\/p>\n<p><code>of<\/code><\/p>\n<p><em>Exercise 6<\/em><\/p>\n<p>What is the expected output of the following code?<\/p>\n<pre class=\"lang:default decode:true \">the_list = ['Where', 'are', 'the', 'snows?']\r\ns = '*'.join(the_list)\r\nprint(s)<\/pre>\n<p>&nbsp;<\/p>\n<p><code>Where*are*the*snows?<\/code><\/p>\n<p><em>Exercise 7<\/em><\/p>\n<p>What is the expected output of the following code?<\/p>\n<pre class=\"lang:default decode:true \">s = 'It is either easy or impossible'\r\ns = s.replace('easy', 'hard').replace('im', '')\r\nprint(s)<\/pre>\n<p>&nbsp;<\/p>\n<p><code>It is either hard or possible<\/code><\/p>\n<p><strong>Slicing<\/strong><\/p>\n<p>The syntax is:<\/p>\n<pre class=\"lang-py s-code-block\"><code data-highlighted=\"yes\" class=\"hljs language-python\">a[start:stop]  <span class=\"hljs-comment\"># items start through stop-1<\/span>\r\na[start:]      <span class=\"hljs-comment\"># items start through the rest of the array<\/span>\r\na[:stop]       <span class=\"hljs-comment\"># items from the beginning through stop-1<\/span>\r\na[:]           <span class=\"hljs-comment\"># a copy of the whole array<\/span>\r\n<\/code><\/pre>\n<p>There is also the <code>step<\/code> value, which can be used with any of the above:<\/p>\n<pre class=\"lang-py s-code-block\"><code data-highlighted=\"yes\" class=\"hljs language-python\">a[start:stop:step] <span class=\"hljs-comment\"># start through not past stop, by step<\/span>\r\n<\/code><\/pre>\n<p>The key point to remember is that the <code>:stop<\/code> value represents the first value that is <em>not<\/em> in the selected slice. So, the difference between <code>stop<\/code> and <code>start<\/code> is the number of elements selected (if <code>step<\/code> is 1, the default).<\/p>\n<p>The other feature is that <code>start<\/code> or <code>stop<\/code> may be a <em>negative<\/em> number, which means it counts from the end of the array instead of the beginning. So:<\/p>\n<pre class=\"lang-py s-code-block\"><code data-highlighted=\"yes\" class=\"hljs language-python\">a[-<span class=\"hljs-number\">1<\/span>]    <span class=\"hljs-comment\"># last item in the array<\/span>\r\na[-<span class=\"hljs-number\">2<\/span>:]   <span class=\"hljs-comment\"># last two items in the array<\/span>\r\na[:-<span class=\"hljs-number\">2<\/span>]   <span class=\"hljs-comment\"># everything except the last two items<\/span>\r\n<\/code><\/pre>\n<p>Similarly, <code>step<\/code> may be a negative number:<\/p>\n<pre class=\"lang-py s-code-block\"><code data-highlighted=\"yes\" class=\"hljs language-python\">a[::-<span class=\"hljs-number\">1<\/span>]    <span class=\"hljs-comment\"># all items in the array, reversed<\/span>\r\na[<span class=\"hljs-number\">1<\/span>::-<span class=\"hljs-number\">1<\/span>]   <span class=\"hljs-comment\"># the first two items, reversed<\/span>\r\na[:-<span class=\"hljs-number\">3<\/span>:-<span class=\"hljs-number\">1<\/span>]  <span class=\"hljs-comment\"># the last two items, reversed<\/span>\r\na[-<span class=\"hljs-number\">3<\/span>::-<span class=\"hljs-number\">1<\/span>]  <span class=\"hljs-comment\"># everything except the last two items, reversed<\/span>\r\n<\/code><\/pre>\n<p>Python is kind to the programmer if there are fewer items than you ask for. For example, if you ask for <code>a[:-2]<\/code> and <code>a<\/code> only contains one element, you get an empty list instead of an error. Sometimes you would prefer the error, so you have to be aware that this may happen.<\/p>\n<pre class=\"lang:default decode:true \">a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\r\nprint(a[::-3]) #  [9, 6, 3, 0]<\/pre>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<p><strong>Comparing strings<\/strong><\/p>\n<p>1. Strings can be compared to strings using general comparison operators, but comparing them to numbers gives no reasonable result, because no string can be equal to any number. <strong>Comparing strings against numbers is generally a bad idea.<\/strong> For example:<\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li><code>string == number<\/code> is always False;<\/li>\n<li><code>string != number<\/code> is always True;<\/li>\n<li><code>string &gt;= number<\/code> always raises an TypeError exception.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true \">'alpha' &lt; 'alphabet'<\/pre>\n<p><code>True<\/code><\/p>\n<p>String comparison is always case-sensitive (upper-case letters are taken as lesser than lower-case).<\/p>\n<pre class=\"lang:default decode:true\">'beta' &gt; 'Beta'<\/pre>\n<p><code>True<\/code><\/p>\n<p>Let&#8217;s check it:<\/p>\n<pre class=\"lang:default decode:true \">'10' == 10\r\n'10' != 10\r\n'10' == 1\r\n'10' != 1\r\n'10' &gt; 10<\/pre>\n<p>The results in this case are:<br \/>\n<code>False<\/code><br \/>\n<code>True<\/code><br \/>\n<code>False<\/code><br \/>\n<code>True<\/code><br \/>\n<code>TypeError exception<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>2. Sorting lists of strings can be done by:<\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li>a function named <code>sorted()<\/code>, creating a new, sorted list;<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true\"># Demonstrating the sorted() function:\r\nfirst_greek = ['omega', 'alpha', 'pi', 'gamma']\r\nfirst_greek_2 = sorted(first_greek)\r\n\r\nprint(first_greek)\r\nprint(first_greek_2)<\/pre>\n<p><code>['omega', 'alpha', 'pi', 'gamma']<\/code><\/p>\n<p><code>['alpha', 'gamma', 'omega', 'pi']<\/code><\/p>\n<p>&nbsp;<\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li>a method named <code>sort()<\/code>, which sorts the list in place<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true \"># Demonstrating the sort() method:\r\nsecond_greek = ['omega', 'alpha', 'pi', 'gamma']\r\nprint(second_greek)\r\n\r\nsecond_greek.sort()\r\nprint(second_greek)<\/pre>\n<p><code>['omega', 'alpha', 'pi', 'gamma']<\/code><\/p>\n<p><code>['alpha', 'gamma', 'omega', 'pi']<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>3. A number can be converted to a string using the<code> str()<\/code> function.<\/p>\n<pre class=\"lang:default decode:true\">itg = 13\r\nflt = 1.3\r\nsi = str(itg)\r\nsf = str(flt)\r\n\r\nprint(si + ' ' + sf)<\/pre>\n<p>The code outputs:<br \/>\n<code>13 1.3<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>4. A string can be converted to a number (although not every string) using either the<code> int()<\/code> or<code> float()<\/code> function. The conversion fails if a string doesn&#8217;t contain a valid number image (an exception is raised then).<\/p>\n<pre class=\"lang:default decode:true \">si = '13'\r\nsf = '1.3'\r\nitg = int(si)\r\nflt = float(sf)\r\n\r\nprint(itg + flt)<\/pre>\n<p>This is what you&#8217;ll see in the console:<br \/>\n<code>14.3<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 1<\/em><\/p>\n<p>Which of the following lines describe a true condition?<br \/>\n<code>'smith' &gt; 'Smith'<\/code><br \/>\n<code>'Smiths' &lt; 'Smith'<\/code><br \/>\n<code>'Smith' &gt; '1000'<\/code><br \/>\n<code>'11' &lt; '8'<\/code><\/p>\n<p>1, 3 and 4<\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 2<\/em><\/p>\n<p>What is the expected output of the following code?<\/p>\n<pre class=\"lang:default decode:true\">s1 = 'Where are the snows of yesteryear?'\r\ns2 = s1.split()\r\ns3 = sorted(s2)\r\nprint(s3[1])\r\nprint(s3)<\/pre>\n<p><code>are<\/code><\/p>\n<p><code>['Where', 'are', 'of', 'snows', 'the', 'yesteryear?']<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 3<\/em><\/p>\n<p>What is the expected result of the following code?<\/p>\n<pre class=\"lang:default decode:true \">s1 = '12.8'\r\ni = int(s1)\r\ns2 = str(i)\r\nf = float(s2)\r\nprint(s1 == s2)<\/pre>\n<p>The code raises a ValueError exception because you can&#8217;t <code>int('12.8')<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 4<\/em><\/p>\n<p>What will be printed to the monitor ?<\/p>\n<pre class=\"lang:default decode:true \">w = 'Luke'\r\nx = 'luke'\r\ny = '10'\r\nz = '5'\r\nprint(w &lt; x and y &lt; z)\r\nprint(x &gt; y and w &gt; z)<\/pre>\n<p>This question is all about string comparison.<\/p>\n<p>As a reminder :<\/p>\n<p>-&gt; when comparing strings, Python <strong>compares code point values<\/strong>, character by character.<\/p>\n<p>-&gt; string comparison is case-sensitive : <strong>upper-case letters are taken as lesser than lower-case<\/strong><\/p>\n<p>-&gt; when comparing two strings of different lengths and the shorter one is identical to the longer one&#8217;s beginning, the <strong>longer string is considered greater<\/strong>.<\/p>\n<p>-&gt; when comparing a string to a number (integer or float), the only comparisons you can perform are with the operators\u00a0 <code>==<\/code> and <code>!=<\/code> operators &#8211; other comparison operators (<code>&gt;<\/code>, <code>&lt;<\/code>) will raise an exception.<\/p>\n<p>-&gt; code points of number characters (0..9) are less than code points of upper-case characters (A..Z)<\/p>\n<p>-&gt; code points of upper-case characters (A..Z) are less than code points of lower-case characters (a..z)<\/p>\n<p><em>Note <\/em>: function <code>ord()<\/code>\u00a0 returns the code point of a given character.<\/p>\n<p>So, in the above question :<\/p>\n<p><code>'Luke' &lt; 'luke'<\/code>\u00a0 \u00a0is <code>True<\/code>\u00a0 ( upper-case <code>'L'<\/code>\u00a0 has a smaller code point than lower-case <code>'l'<\/code> )<\/p>\n<p><code>'10' &lt; '5'<\/code>\u00a0 \u00a0is <code>True<\/code> (<code>'1'<\/code> has a smaller code point than\u00a0 <code>'5'<\/code> )<\/p>\n<p>So : <code>print('Luke' &lt; 'luke' and '10' &lt; '5')<\/code>\u00a0 will return <code>True<\/code><\/p>\n<p><code>'luke' &gt; '10'<\/code>\u00a0 \u00a0is <code>True<\/code>\u00a0 ( lower-case <code>'l'<\/code>\u00a0 has a greater code point than <code>'1'<\/code> )<\/p>\n<p><code>'Luke' &gt; '5'<\/code>\u00a0 \u00a0is <code>True<\/code> (upper-case <code>'L'<\/code> has a greater code point than <code>'5'<\/code> )<\/p>\n<p>So : <code>print('luke' &gt; '10' and 'Luke' &gt; '5')<\/code>\u00a0 will return <code>True<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 5<\/em><\/p>\n<div id=\"question-prompt\" class=\" ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>What is the output of the following code snippet?<\/p>\n<p><code>print(str(2\/3)[-1]) <\/code><\/p>\n<p><code>6<\/code><\/p>\n<p><strong>Explanation:<\/strong><\/p>\n<p><code>2\/3<\/code> is a valid operation and evaluates to <code>0.66666666666666666<\/code>\u00a0 (a float).<\/p>\n<p>The <code>str()<\/code> function will convert the float to a string.<\/p>\n<p><code>str(2\/3)[-1] <\/code>\u00a0 \u00a0is a slicing operation on the string and will return the last character of the string which is <code>6<\/code> .<\/p>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Ex. 6<\/p>\n<p>What is the expected output of the following snippet ?<\/p>\n<pre class=\"lang:default decode:true \">    x = 'Yoda 7'\r\n    if x.isalpha():\r\n        print(1)\r\n    elif x.isdigit():\r\n        print(2)\r\n    elif x.isalnum():\r\n        print(3)\r\n    else:\r\n        print(4)<\/pre>\n<p>&nbsp;<\/p>\n<p><code>4<\/code><\/p>\n<p><strong>Explanation:<\/strong><\/p>\n<p><code>isalpha()<\/code> checks if the string contains<strong> only alphabetical characters (letters)<\/strong>, and returns <code>True<\/code> or <code>False<\/code> according to the result.<\/p>\n<p><code>isdigit()<\/code> checks if the string contains<strong> only digits<\/strong>, and returns <code>True<\/code> or <code>False<\/code> according to the result.<\/p>\n<p><code>isalnum()<\/code> checks if the string contains<strong> only digits or alphabetical characters (letters)<\/strong>, and returns <code>True<\/code> or <code>False<\/code> according to the result.<\/p>\n<p>Note that <strong>a space is neither a digit nor a letter.<\/strong><\/p>\n<p>So, the above code returns <code>4<\/code>.<\/p>\n<p>&nbsp;<\/p>\n<p>Ex. 7<\/p>\n<p>What is the expected output of the following code snippet ?<\/p>\n<pre class=\"lang:default decode:true \">    my_list = ['apple', 'koala', '1234Bz', 'Polo']\r\n    my_list.sort(key = lambda x: x[::-1])\r\n    print(my_list[0])<\/pre>\n<p><strong>Explanation:<\/strong><\/p>\n<p><code>sort()<\/code> is a method of the list class. It is similar to <code>sorted()<\/code> but with a few differences :<\/p>\n<p>&#8211; <code>sorted()<\/code> returns a new sorted list, while <code>sort()<\/code> sorts the list in place<\/p>\n<p>&#8211; <code>sorted()<\/code> can be used with an iterable (like a string for example), while <code>sort()<\/code> can only be used with lists.<\/p>\n<p>Both <code>sort()<\/code> and <code>sorted()<\/code> can be used with one of these optional keyword arguments:<\/p>\n<p>&#8211; <code>reverse<\/code> : if set to True, sorting is done in a descending order &#8211; if set to <code>False<\/code>, sorting is done in ascending order.<\/p>\n<p>&#8211; <code>key<\/code> : this argument is a function which will be used on each value in the list being sorted to determine the resulting order.<\/p>\n<p>In the above function, they <code>key<\/code> argument is used in the <code>sort()<\/code> method, with <code>key = lambda x: x[::-1]<\/code>\u00a0 -&gt; this is a lambda function that will be applied on each element of <code>my_list<\/code>\u00a0 &#8211; this lambda function will reverse the order of the characters for each of the strings in <code>my_list<\/code>\u00a0. For example : <code>'apple'<\/code> will become <code>'elppa'<\/code> ; <code>'koala'<\/code> will become <code>'alaok'<\/code>, etc.. The <code>sort()<\/code> method will then perform the sorting operation based on the first letter of these modified strings (<code>'elppa'<\/code>, <code>'alaok'<\/code>, etc&#8230;) but the original strings are still returned (they are not actually modified by the function identified by <code>key <\/code>&#8211; the function in <code>key<\/code> is only used to figure out <em>what <\/em>to sort).<\/p>\n<p>Based on this, <code>'alaok'<\/code> would be the first string (because it starts with character &#8216;a&#8217; which has the smallest Unicode value among lowercase letters). The second one will be <code>'elppa'<\/code>. Third one is <code>'oloP'<\/code> and last one is <code>'zB4321'<\/code>.<\/p>\n<p>And so, <code>my_list.sort(key = lambda x: x[::-1])<\/code>\u00a0 will return :<\/p>\n<p><code>['koala', 'apple', 'Polo', '1234Bz']<\/code>\u00a0 (remember that the list is not modified by the function in <code>key<\/code>, it is just used for ordering).<\/p>\n<p>&nbsp;<\/p>\n<p>Ex. 8<\/p>\n<p>Which statement is true about the two objects below ? (Pick two)<\/p>\n<pre class=\"lang:default decode:true\">str1='Hello'\r\nstr2='Hello'<\/pre>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-correct--PLOEU\" data-purpose=\"answer\">\n<div><span class=\"result-pane--answer-by-user-label--PSH86 ud-heading-xs\" data-purpose=\"answer-result-header-user-label\">A. <\/span><code>id(str1) == id(str2)<\/code><\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-incorrect--vFyOv\" data-purpose=\"answer\">\n<div><span class=\"result-pane--answer-by-user-label--PSH86 ud-heading-xs\" data-purpose=\"answer-result-header-user-label\">B. <\/span><code>str1 is not str2<\/code><\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-correct--PLOEU\" data-purpose=\"answer\">\n<div><span class=\"result-pane--answer-by-user-label--PSH86 ud-heading-xs\" data-purpose=\"answer-result-header-user-label\">C.<\/span> <code>str1[::1] == str2<\/code><\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>D. <code>id(str1) != id(str2)<\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--question-related-fields--c3m--\">\n<div class=\"overall-explanation-pane--overall-explanation--G-hLQ ud-form-group\">\n<div id=\"overall-explanation\" class=\"ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p><em>Explanation:<\/em><\/p>\n<p>A string is immutable and if you create two strings with the same value they will point to the same object.<\/p>\n<p><code>id()<\/code> function returns the identity of the object. This is an integer that is unique for the given object and remains constant during its lifetime.<\/p>\n<p>Since <code>str1 <\/code>and <code>str2 <\/code>point to the same object, their identity is the same.<\/p>\n<p>so <code>id(str1) == id(str2) <\/code>is <code>True<\/code><\/p>\n<p>Obviously\u00a0 <code>id(str1) != id(str2)<\/code>\u00a0 \u00a0is <code>False<\/code><\/p>\n<p><code>str1[::1] <\/code> is a slicing operation on the string <code>str1<\/code>\u00a0 It returns all characters from the first index of the string to the last index, with a step of 1 character &#8211; in other words, the whole string which is <code>Hello<\/code>. And so <code>str1[::1] == str2<\/code> is <code>True<\/code>.<\/p>\n<p>Finally, the <code>is<\/code> and <code>is not<\/code> operators check whether both operands refer to the same object or not.<\/p>\n<p>As explained above, <code>str1 <\/code>and <code>str2 <\/code>do refer to the same object, so <code>str1 is str2<\/code>\u00a0 is <code>True <\/code>and\u00a0 <code>str1 is not str2<\/code> is <code>False<\/code>.<\/p>\n<p>Try it yourself:<\/p>\n<\/div>\n<\/div>\n<\/div>\n<pre class=\"lang:default decode:true \">    str1='Hello'\r\n    str2='Hello'\r\n     \r\n    print(id(str1))                # 140473762198000\r\n    print(id(str2))                # 140473762198000\r\n    print(id(str1) == id(str2))    # True\r\n    print(id(str1) != id(str2))    # False\r\n    print(str1[::1])               # Hello\r\n    print(str1[::1] == str2)       # True\r\n    print(str1 is str2)            # True\r\n    print(str1 is not str2)        # False<\/pre>\n<p>AC<\/p>\n<p>&nbsp;<\/p>\n<p>Ex. 9<\/p>\n<p>What is the expected output of the following code, assuming there is no whitespace after the 3rd quote of the first line of code?<\/p>\n<pre class=\"lang:default decode:true \">    my_str = '''\r\n    #'''\r\n     \r\n    print(len(my_str))<\/pre>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-correct--PLOEU\" data-purpose=\"answer\">\n<div><span class=\"result-pane--answer-by-user-label--PSH86 ud-heading-xs\" data-purpose=\"answer-result-header-user-label\">A. <\/span><code>2<\/code><\/div>\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>B. <code>7<\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>C. <code>8<\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>D. <code>4<\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>Explanation:<\/p>\n<p><code>'''<\/code> allows to delimit a <strong>multi-line string<\/strong>.<\/p>\n<p><code>my_str<\/code> is a 2-lines string : the first line only includes the special character for a new line : <code>\\n<\/code> &#8211; it counts as one character. The 2nd line only includes the # character (which is not considered as a comment in this case).<\/p>\n<p>So, the total length of the string is : 2.<\/p>\n<p>&nbsp;<\/p>\n<p>Ex.10<\/p>\n<p>Knowing that <code>ord('a')<\/code> has a value of\u00a0 <code>97<\/code>, which code below will print <code>bee<\/code> to the monitor ?<\/p>\n<p>A. <code>print(chr(98), chr(101), chr(101), sep=',')<\/code><\/p>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>B. <code>print(''.join([str(ord('b')), str(ord('e')), str(ord('e'))]))<\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-correct--PLOEU\" data-purpose=\"answer\">\n<div><span class=\"result-pane--answer-by-user-label--PSH86 ud-heading-xs\" data-purpose=\"answer-result-header-user-label\">C. <\/span><code>print(chr(98) + 2*chr(101))<\/code><\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>D. <code>print(chr(ord('a')+1), chr(ord('a') + 4), chr(ord('a') + 4))<\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--question-related-fields--c3m--\">\n<div class=\"overall-explanation-pane--overall-explanation--G-hLQ ud-form-group\"><label class=\"ud-heading-md ud-form-label ud-heading-sm\" for=\"form-group--2925\"><\/label><code><\/code><\/p>\n<div id=\"overall-explanation\" class=\"ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p><em>Explanation:<\/em><\/p>\n<p>Function <code>ord()<\/code> returns the Unicode code of a given character.<\/p>\n<p>Function <code>chr()<\/code> returns the corresponding character from a given Unicode code.<\/p>\n<p>The Unicode code of <code>a<\/code> is given in the question (you don&#8217;t have to remember this for the test !) : <code>97<\/code>.\u00a0 We can easily deduct the Unicode code of characters <code>b<\/code> and <code>e<\/code> :<\/p>\n<p><code>a --&gt; 97<\/code><\/p>\n<p><code>b --&gt; 98<\/code><\/p>\n<p><code>c --&gt; 99<\/code><\/p>\n<p><code>d --&gt; 100<\/code><\/p>\n<p><code>e --&gt; 101<\/code><\/p>\n<p>Now, let&#8217;s review each suggested answers:<\/p>\n<p>&#8211;&gt; <code>print(chr(98) + 2*chr(101))<\/code><\/p>\n<p>This is equivalent to <code>print('b' + 2*'e')<\/code> , which will print <code>bee<\/code> (<code>+<\/code> concatenates string and <code>*<\/code> repeats a string)<\/p>\n<p>&#8211;&gt; <code>print(chr(ord('a')+1), chr(ord('a') + 4), chr(ord('a') + 4))<\/code><\/p>\n<p>This is equivalent to <code>print('b', 'e', 'e')<\/code>\u00a0 which will print <code>b e e<\/code> (notice the space between the characters).<\/p>\n<p>&#8211;&gt; <code>print(chr(98), chr(101), chr(101), sep=',')<\/code><\/p>\n<p>This is equivalent to <code>print('b', 'e', 'e', sep=',')<\/code>\u00a0 which will print <code>b,e,e<\/code> (notice the comma between the characters).<\/p>\n<p>&#8211;&gt; <code>print(''.join([str(ord('b')), str(ord('e')), str(ord('e'))]))<\/code><\/p>\n<p>This is equivalent to <code>print(''.join(['98', '101', '101']))<\/code>\u00a0 which will print string <code>98101101<\/code>.<\/p>\n<p>Try it yourself:<\/p>\n<pre class=\"lang:default decode:true \">    print(chr(98) + 2*chr(101))                                     # bee\r\n    print(chr(ord('a')+1), chr(ord('a') + 4), chr(ord('a') + 4))    # b e e\r\n    print(chr(98), chr(101), chr(101), sep=',')                     # b,e,e\r\n    print(''.join([str(ord('b')), str(ord('e')), str(ord('e'))]))   # 98101101<\/pre>\n<p>&nbsp;<\/p>\n<\/div>\n<\/div>\n<\/div>\n<p>&nbsp;<\/p>\n<p><strong>The Caesar Cipher: encrypting a message<\/strong><\/p>\n<p>This cipher was (probably) invented and used by Gaius Julius Caesar and his troops during the Gallic Wars. The idea is rather simple &#8211; every letter of the message is replaced by its nearest consequent (A becomes B, B becomes C, and so on). The only exception is Z, which becomes A.<\/p>\n<pre class=\"lang:default decode:true \"># Caesar cipher.\r\ntext = input(\"Enter your message: \")\r\ncipher = ''\r\nfor char in text:\r\n    if not char.isalpha():\r\n        continue\r\n    char = char.upper()\r\n    code = ord(char) + 1\r\n    if code &gt; ord('Z'):\r\n        code = ord('A')\r\n    cipher += chr(code)\r\n\r\nprint(cipher)<\/pre>\n<p>&nbsp;<\/p>\n<p><strong>The Caesar Cipher: decrypting a message<\/strong><\/p>\n<pre class=\"lang:default decode:true \"># Caesar cipher - decrypting a message.\r\ncipher = input('Enter your cryptogram: ')\r\ntext = ''\r\nfor char in cipher:\r\n    if not char.isalpha():\r\n        continue\r\n    char = char.upper()\r\n    code = ord(char) - 1\r\n    if code &lt; ord('A'):\r\n        code = ord('Z')\r\n    text += chr(code)\r\n\r\nprint(text)<\/pre>\n<p>&nbsp;<\/p>\n<p><strong>The Numbers Processor<\/strong><\/p>\n<p>The third program shows a simple method allowing you to input a line filled with numbers, and to process them easily. The processing will be extremely easy &#8211; we want the numbers to be summed.<\/p>\n<pre class=\"lang:default decode:true \"># Numbers Processor.\r\n\r\nline = input(\"Enter a line of numbers - separate them with spaces: \")\r\nstrings = line.split()\r\ntotal = 0\r\ntry:\r\n    for substr in strings:\r\n        total += float(substr)\r\n    print(\"The total is:\", total)\r\nexcept:\r\n    print(substr, \"is not a number.\")<\/pre>\n<p><code>Enter a line of numbers - separate them with spaces: 12 4<\/code><\/p>\n<p><code>The total is: 16.0<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><strong>The IBAN Validator<\/strong><\/p>\n<p>The fourth program implements (in a slightly simplified form) an algorithm used by European banks to specify account numbers. The standard named IBAN (International Bank Account Number) provides a simple and fairly reliable method for validating account numbers against simple typos that can occur during rewriting of the number.<\/p>\n<p>The standard says that validation requires the following steps (according to Wikipedia):<\/p>\n<ul>\n<li>(step 1) Check that the total IBAN length is correct as per the country (this program won&#8217;t do that, but you can modify the code to meet this requirement if you wish; note: you have to teach the code all the lengths used in Europe)<\/li>\n<li>(step 2) Move the four initial characters to the end of the string (i.e., the country code and the check digits)<\/li>\n<li>(step 3) Replace each letter in the string with two digits, thereby expanding the string, where A = 10, B = 11 &#8230; Z = 35;<\/li>\n<li>(step 4) Interpret the string as a decimal integer and compute the remainder of that number by modulo-dividing it by 97; If the remainder is 1, the check digit test is passed and the IBAN might be valid.<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true \"># IBAN Validator.\r\n\r\niban = input(\"Enter IBAN, please: \")\r\niban = iban.replace(' ','')\r\n\r\nif not iban.isalnum():\r\n    print(\"You have entered invalid characters.\")\r\nelif len(iban) &lt; 15:\r\n    print(\"IBAN entered is too short.\")\r\nelif len(iban) &gt; 31:\r\n    print(\"IBAN entered is too long.\")\r\nelse:\r\n    iban = (iban[4:] + iban[0:4]).upper()\r\n    iban2 = ''\r\n    for ch in iban:\r\n        if ch.isdigit():\r\n            iban2 += ch\r\n        else:\r\n            iban2 += str(10 + ord(ch) - ord('A'))\r\n    iban = int(iban2)\r\n    if iban % 97 == 1:\r\n        print(\"IBAN entered is valid.\")\r\n    else:\r\n        print(\"IBAN entered is invalid.\")<\/pre>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>1. Python strings are immutable sequences and can be indexed, sliced, and iterated like any other sequence, as well as being subject to the in and not in operators. There are two kinds of strings in Python:<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[100],"tags":[],"_links":{"self":[{"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/posts\/5976"}],"collection":[{"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/comments?post=5976"}],"version-history":[{"count":48,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/posts\/5976\/revisions"}],"predecessor-version":[{"id":6280,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/posts\/5976\/revisions\/6280"}],"wp:attachment":[{"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/media?parent=5976"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/categories?post=5976"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/tags?post=5976"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}