avatarDeck451

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

23528

Abstract

">result</span>)</pre></div><div id="1918"><pre><span class="hljs-comment"># non-alphabet string</span> my_second_string = <span class="hljs-string">"Ab."</span> <span class="hljs-literal">result</span> = my_second_string.isalpha() print(<span class="hljs-literal">result</span>)</pre></div><div id="12ef"><pre><span class="hljs-comment"># empty string</span> my_empty_string = <span class="hljs-string">""</span> <span class="hljs-literal">result</span> = my_empty_string.isalpha() print(<span class="hljs-literal">result</span>)</pre></div><div id="b765"><pre><span class="hljs-attr">Output:</span> <span class="hljs-literal">True</span> <span class="hljs-literal">False</span> <span class="hljs-literal">False</span></pre></div><h2 id="8ff1">ASCII string</h2><p id="7c18">In other words, we check if the string only contains characters in the current standard ASCII range or not:</p><div id="acc9"><pre><span class="hljs-comment"># construct an ascii string</span> my_string = <span class="hljs-string">"Abc"</span> <span class="hljs-literal">result</span> = my_string.isascii() print(<span class="hljs-literal">result</span>)</pre></div><div id="4f97"><pre><span class="hljs-comment"># empty string</span> my_empty_string = <span class="hljs-string">""</span> <span class="hljs-literal">result</span> = my_empty_string.isascii() print(<span class="hljs-literal">result</span>)</pre></div><div id="2ab4"><pre># non-<span class="hljs-built_in">ascii</span> <span class="hljs-built_in">string</span> my_non_ascii_string = 'This <span class="hljs-built_in">is</span> <span class="hljs-keyword">not</span> an <span class="hljs-built_in">ascii</span> <span class="hljs-built_in">string</span> \u0080' result = my_non_ascii_string.isascii() <span class="hljs-built_in">print</span>(result)</pre></div><div id="7f7c"><pre><span class="hljs-attr">Output:</span> <span class="hljs-literal">True</span> <span class="hljs-literal">True</span> <span class="hljs-literal">False</span></pre></div><h2 id="9b2e">Decimal string</h2><p id="9281">It may be that sometimes a requirement is that a string is composed of only decimal characters. To that end, <code>string.isdecimal()</code> is available for us. Let’s see how that works:</p><div id="dde7"><pre><span class="hljs-comment"># construct a non-decimal string</span> my_string = <span class="hljs-string">"Abc"</span> <span class="hljs-literal">result</span> = my_string.isdecimal() print(<span class="hljs-literal">result</span>)</pre></div><div id="27aa"><pre><span class="hljs-comment"># construct a decimal string</span> my_decimal_string = <span class="hljs-string">"123"</span> <span class="hljs-literal">result</span> = my_decimal_string.isdecimal() print(<span class="hljs-literal">result</span>)</pre></div><div id="3230"><pre><span class="hljs-comment"># construct a decimal string with a decimal point</span> my_other_string = <span class="hljs-string">"123.5"</span> <span class="hljs-literal">result</span> = my_other_string.isdecimal() print(<span class="hljs-literal">result</span>)</pre></div><div id="f388"><pre><span class="hljs-comment"># empty string</span> my_empty_string = <span class="hljs-string">""</span> <span class="hljs-literal">result</span> = my_empty_string.isdecimal() print(<span class="hljs-literal">result</span>)</pre></div><div id="d6e3"><pre><span class="hljs-comment"># still a non-decimal string</span> my_non_decimal_string = <span class="hljs-string">"²3455"</span> <span class="hljs-literal">result</span> = my_non_decimal_string.isdecimal() print(<span class="hljs-literal">result</span>)</pre></div><div id="8e50"><pre><span class="hljs-attr">Output:</span> <span class="hljs-literal">False</span> <span class="hljs-literal">True</span> <span class="hljs-literal">False</span> <span class="hljs-literal">False</span> <span class="hljs-literal">False</span></pre></div><p id="891e">It’s only decimal if every character is a decimal character. As we could see, superscript (exponent) characters or decimal points cause the check to fail, returning <code>False</code>.</p><h2 id="c4fc">Digit string</h2><p id="0a56">Similarly to <code>string.isdecimal()</code>, the <code>string.isdigit()</code> method checks if all characters are string representations of digits. Unlike <code>string.isdecimal()</code>, though, superscript (exponent) characters are considered digits:</p><div id="fc19"><pre><span class="hljs-comment"># construct a non-digit string</span> my_string = <span class="hljs-string">"Abc"</span> <span class="hljs-literal">result</span> = my_string.isdigit() print(<span class="hljs-literal">result</span>)</pre></div><div id="4f0c"><pre><span class="hljs-comment"># empty string</span> my_empty_string = <span class="hljs-string">""</span> <span class="hljs-literal">result</span> = my_empty_string.isdigit() print(<span class="hljs-literal">result</span>)</pre></div><div id="76b6"><pre><span class="hljs-comment"># digit string</span> my_digit_string = <span class="hljs-string">"²3455"</span> <span class="hljs-literal">result</span> = my_digit_string.isdigit() print(<span class="hljs-literal">result</span>)</pre></div><div id="534f"><pre><span class="hljs-comment"># a roman numeral string</span> my_roman_string = <span class="hljs-string">"ↁ"</span> <span class="hljs-literal">result</span> = my_roman_string.isdigit() print(<span class="hljs-literal">result</span>)</pre></div><div id="1d06"><pre><span class="hljs-attr">Output:</span> <span class="hljs-literal">False</span> <span class="hljs-literal">False</span> <span class="hljs-literal">True</span> <span class="hljs-literal">False</span></pre></div><h2 id="4e3e">Test if string is a valid identifier</h2><p id="ad6b">The <code>string.isidentifier()</code> method will check if it can be considered a valid identifier in Python. An identifier is considered valid in Python if it only contains alphabet characters (letters), numbers, and underscores. Furthermore, it cannot contain spaces and cannot start with a digit.</p><div id="049d"><pre><span class="hljs-comment"># valid identifier</span> my_string = <span class="hljs-string">"Abc"</span> <span class="hljs-literal">result</span> = my_string.isidentifier() print(<span class="hljs-literal">result</span>)</pre></div><div id="ae7d"><pre><span class="hljs-comment"># invalid identifier</span> my_other_string = <span class="hljs-string">"Abc def"</span> <span class="hljs-literal">result</span> = my_other_string.isidentifier() print(<span class="hljs-literal">result</span>)</pre></div><div id="675c"><pre><span class="hljs-comment"># also invalid identifier</span> another_string = <span class="hljs-string">"123def"</span> <span class="hljs-literal">result</span> = another_string.isidentifier() print(<span class="hljs-literal">result</span>)</pre></div><div id="7b00"><pre><span class="hljs-comment"># empty string</span> my_empty_string = <span class="hljs-string">""</span> <span class="hljs-literal">result</span> = my_empty_string.isidentifier() print(<span class="hljs-literal">result</span>)</pre></div><div id="434b"><pre><span class="hljs-attr">Output:</span> <span class="hljs-literal">True</span> <span class="hljs-literal">False</span> <span class="hljs-literal">False</span> <span class="hljs-literal">False</span></pre></div><h2 id="13fe">Lowercase string</h2><p id="2cea">To test if all characters in one given string are lowercase, just use <code>string.islower()</code>:</p><div id="ac98"><pre><span class="hljs-comment"># not lowercase</span> my_string = <span class="hljs-string">"Abc"</span> <span class="hljs-literal">result</span> = my_string.islower() print(<span class="hljs-literal">result</span>)</pre></div><div id="2bfa"><pre><span class="hljs-comment"># lowercase</span> my_second_string = <span class="hljs-string">"def"</span> <span class="hljs-literal">result</span> = my_second_string.islower() print(<span class="hljs-literal">result</span>)</pre></div><div id="4241"><pre><span class="hljs-comment"># empty string</span> my_empty_string = <span class="hljs-string">""</span> <span class="hljs-literal">result</span> = my_empty_string.islower() print(<span class="hljs-literal">result</span>)</pre></div><div id="b35a"><pre><span class="hljs-attr">Output:</span> <span class="hljs-literal">False</span> <span class="hljs-literal">True</span> <span class="hljs-literal">False</span></pre></div><h2 id="3e92">Check if string is numeric</h2><p id="0005">The <code>string.isnumeric()</code> method checks if all characters within the string are numeric. Very similar to the <code>string.isdigit()</code> method, except for the case of Roman numeral strings. This is the main difference between <code>isnumeric()</code> and <code>isdigit()</code>, as the former will return <code>True</code> in the case of a Roman numeral string, while the latter will return <code>False</code>:</p><div id="4e00"><pre><span class="hljs-comment"># a non-numeric string</span> my_string = <span class="hljs-string">"Abc"</span> <span class="hljs-literal">result</span> = my_string.isnumeric() print(<span class="hljs-literal">result</span>)</pre></div><div id="39d8"><pre><span class="hljs-comment"># yet another non-numeric string</span> my_second_string = <span class="hljs-string">"12a"</span> <span class="hljs-literal">result</span> = my_second_string.isnumeric() print(<span class="hljs-literal">result</span>)</pre></div><div id="0e68"><pre><span class="hljs-comment"># a numeric string</span> my_numeric_string = <span class="hljs-string">"²3455"</span> <span class="hljs-literal">result</span> = my_numeric_string.isnumeric() print(<span class="hljs-literal">result</span>)</pre></div><div id="2f82"><pre><span class="hljs-comment"># an empty string</span> my_empty_string = <span class="hljs-string">""</span> <span class="hljs-literal">result</span> = my_empty_string.isnumeric() print(<span class="hljs-literal">result</span>)</pre></div><div id="241e"><pre><span class="hljs-comment"># a roman numeral string</span> my_roman_string = <span class="hljs-string">"ↁ"</span> <span class="hljs-literal">result</span> = my_roman_string.isnumeric() print(<span class="hljs-literal">result</span>)</pre></div><div id="2503"><pre><span class="hljs-attr">Output:</span> <span class="hljs-literal">False</span> <span class="hljs-literal">False</span> <span class="hljs-literal">True</span> <span class="hljs-literal">False</span> <span class="hljs-literal">True</span></pre></div><h2 id="c7d1">Printable strings</h2><p id="a25d">There is a way to check if all characters in a string are printable. Let’s demonstrate the <code>string.isprintable()</code> method:</p><div id="e2e2"><pre><span class="hljs-comment"># printable string</span> my_string = <span class="hljs-string">"Abc"</span> <span class="hljs-literal">result</span> = my_string.isprintable() print(<span class="hljs-literal">result</span>)</pre></div><div id="7e54"><pre><span class="hljs-comment"># empty string</span> my_empty_string = <span class="hljs-string">""</span> <span class="hljs-literal">result</span> = my_empty_string.isprintable() print(<span class="hljs-literal">result</span>)</pre></div><div id="4126"><pre><span class="hljs-comment"># non-printable string</span> my_non_printable_string = <span class="hljs-string">"\nDef"</span> <span class="hljs-literal">result</span> = my_non_printable_string.isprintable() print(<span class="hljs-literal">result</span>)</pre></div><div id="f617"><pre><span class="hljs-attr">Output:</span> <span class="hljs-literal">True</span> <span class="hljs-literal">True</span> <span class="hljs-literal">False</span></pre></div><p id="97ae">Turns out, empty strings are printable :)</p><h2 id="f101">Space strings</h2><p id="f030">If a string is only containing spaces or tabs, the <code>string.isspace()</code> method will come in handy:</p><div id="0de9"><pre><span class="hljs-comment"># regular string</span> my_string = <span class="hljs-string">"Abc"</span> <span class="hljs-literal">result</span> = my_string.isspace() print(<span class="hljs-literal">result</span>)</pre></div><div id="5236"><pre># <span class="hljs-literal">empty</span> string my_empty_string = <span class="hljs-string">""</span> result = my_empty_string.<span class="hljs-keyword">is</span><span class="hljs-built_in">space</span>() pr<span class="hljs-built_in">int</span>(result)</pre></div><div id="1dfd"><pre><span class="hljs-comment"># contains spaces, but not only spaces</span> my_non_space_string = <span class="hljs-string">"De f"</span> <span class="hljs-literal">result</span> = my_non_space_string.isspace() print(<span class="hljs-literal">result</span>)</pre></div><div id="7fa0"><pre><span class="hljs-comment"># whitespace string</span> my_space_string = <span class="hljs-string">"\t"</span> <span class="hljs-literal">result</span> = my_space_string.isspace() print(<span class="hljs-literal">result</span>)</pre></div><div id="f632"><pre><span class="hljs-comment"># another whitespace string</span> my_other_space_string = <span class="hljs-string">"\t "</span> <span class="hljs-literal">result</span> = my_other_space_string.isspace() print(<span class="hljs-literal">result</span>)</pre></div><div id="9cfa"><pre><span class="hljs-attr">Output:</span> <span class="hljs-literal">False</span> <span class="hljs-literal">False</span> <span class="hljs-literal">False</span> <span class="hljs-literal">True</span> <span class="hljs-literal">True</span></pre></div><h2 id="4858">Titlecase string</h2><p id="72fd">A string is considered to be titlecase if the words that make it up are having their first letters capitalized:</p><div id="d5f2"><pre><span class="hljs-comment"># titlecase string</span> my_string = <span class="hljs-string">"Abc D Efg"</span> <span class="hljs-literal">result</span> = my_string.istitle() print(<span class="hljs-literal">result</span>)</pre></div><div id="78c1"><pre><span class="hljs-comment"># not a titlecase string</span> my_other_string = <span class="hljs-string">"Abc def"</span> <span class="hljs-literal">result</span> = my_other_string.istitle() print(<span class="hljs-literal">result</span>)</pre></div><div id="b3c9"><pre><span class="hljs-comment"># an empty string</span> my_empty_string = <span class="hljs-string">""</span> <span class="hljs-literal">result</span> = my_empty_string.istitle() print(<span class="hljs-literal">result</span>)</pre></div><div id="f7bb"><pre><span class="hljs-attr">Output:</span> <span class="hljs-literal">True</span> <span class="hljs-literal">False</span> <span class="hljs-literal">False</span></pre></div><h2 id="9196">String is all uppercase</h2><p id="3f4d">The <code>string</code> class even has a method to check if the string object is exclusively composed of uppercase characters:</p><div id="02db"><pre><span class="hljs-comment"># not an uppercase string</span> my_string = <span class="hljs-string">"Abc"</span> <span class="hljs-literal">result</span> = my_string.isupper() print(<span class="hljs-literal">result</span>)</pre></div><div id="00eb"><pre><span class="hljs-comment"># an uppercase string</span> my_other_string = <span class="hljs-string">"DEF234-78U"</span> <span class="hljs-literal">result</span> = my_other_string.isupper() print(<span class="hljs-literal">result</span>)</pre></div><div id="2ea9"><pre><span class="hljs-comment"># an empty string</span> my_empty_string = <span class="hljs-string">""</span> <span class="hljs-literal">result</span> = my_empty_string.isupper() print(<span class="hljs-literal">result</span>)</pre></div><div id="c0f1"><pre><span class="hljs-attr">Output:</span> <span class="hljs-literal">False</span> <span class="hljs-literal">True</span> <span class="hljs-literal">False</span></pre></div><p id="021f">Note that the uppercase string we tested, <code>DEF234-78U</code>, has been judged as an actual uppercase string, even though it contains digits and other characters, like the dash symbol.</p><h2 id="c592">Join iterable elements into a string</h2><p id="040b">In Python, we can have a list of elements joined into a string, using a separator string:</p><div id="78b6"><pre><span class="hljs-comment"># define the separator string</span> <span class="hljs-attr">my_string</span> = <span class="hljs-string">","</span></pre></div><div id="cab1"><pre><span class="hljs-comment"># construct the iterator</span> <span class="hljs-attr">my_list</span> = [<span class="hljs-string">"a"</span>, <span class="hljs-string">"b"</span>, <span class="hljs-string">"c"</span>]</pre></div><div id="04c1"><pre># <span class="hljs-keyword">join</span> the <span class="hljs-keyword">iterator</span> elements <span class="hljs-keyword">into</span> a <span class="hljs-type">string</span> result = my_string.<span class="hljs-keyword">join</span>(my_list)</pre></div><div id="4738"><pre><span class="hljs-comment"># print the resulting string</span> <span class="hljs-built_in">print</span>(result)</pre></div><div id="dc86"><pre>Output: <span class="hljs-selector-tag">a</span>,<span class="hljs-selector-tag">b</span>,c</pre></div><h2 id="a741">Left justify a string</h2><p id="9f34">Very straightforward, <code>string.ljust()</code> will do just what its name suggests. All it needs is the <code>width</code> of the space in relation to which the justifying takes place and an optional <code>fill character</code> to fill in the rest of the width space we just mentioned:</p><div id="a221"><pre><span class="hljs-comment"># a regular string</span> my_string = <span class="hljs-string">"Abc"</span> <span class="hljs-literal">result</span> = my_string.ljust(<span class="hljs-number">10</span>, <span class="hljs-string">"."</span>) print(<span class="hljs-literal">result</span>)</pre></div><div id="5e13"><pre><span class="hljs-comment"># an empty string</span> my_empty_string = <span class="hljs-string">""</span> <span class="hljs-literal">result</span> = my_empty_string.ljust(<span class="hljs-number">10</span>, <span class="hljs-string">"."</span>) print(<span class="hljs-literal">result</span>)</pre></div><div id="4b6a"><pre>Output: Abc<span class="hljs-params">...</span><span class="hljs-params">...</span>. <span class="hljs-params">...</span><span class="hljs-params">...</span><span class="hljs-params">...</span>.</pre></div><h2 id="4c08">Turn all characters lowercase</h2><p id="ac48">Another simple, straightforward, and very useful method, <code>string.lower()</code> will make sure your string stays lowercase:</p><div id="e1d5"><pre><span class="hljs-comment"># a regular string</span> my_string = <span class="hljs-string">"Abc"</span> <span class="hljs-built_in">result</span> = my_string.<span class="hljs-built_in">lower</span>() print(f<span class="hljs-string">"|{result}|"</span>)</pre></div><div id="3243"><pre><span class="hljs-comment"># an empty string</span> my_empty_string = <span class="hljs-string">""</span> <span class="hljs-built_in">result</span> = my_empty_string.<span class="hljs-built_in">lower</span>() print(f<span class="hljs-string">"|{result}|"</span>)</pre></div><div id="d1fe"><pre>Output: |<span class="hljs-string">abc</span>| ||</pre></div><p id="2318">Had to use pipe symbols to emphasize the empty string result in the second test.</p><h2 id="be47">Strip leading whitespace</h2><p id="f226">Eventually, you’ll stumble upon strings containing leading whitespace, like spaces or tabs. Python allows for a simple way of getting rid of the leading whitespace:</p><div id="490b"><pre><span class="hljs-comment"># construct the string</span> my_string = <span class="hljs-string">" \t Abc Def "</span> <span class="hljs-built_in">print</span>(<span class="hljs-string">f"|<span class="hljs-subst">{my_string}</span>|"</span>)</pre></div><div id="75a1"><pre><span class="hljs-comment"># left-strip the whitespace</span> result = my_string.lstrip() <span class="hljs-built_in">print</span>(<span class="hljs-string">f"|<span class="hljs-subst">{result}</span>|"</span>)</pre></div><div id="7213"><pre><span class="hljs-comment"># try the same with an empty string</span> my_empty_string = <span class="hljs-string">""</span> result = my_empty_string.lstrip() print(f<span class="hljs-string">"|{result}|"</span>)</pre></div><div id="e101"><pre>Output: |<span class="hljs-string"> Abc Def </span>| |<span class="hljs-string">Abc Def </span>| ||</pre></div><p id="95c4">Note that the method did nothing to alter the trailing whitespace, nor the whitespace from between the two substrings. It only affected the leading whitespace characters, effectively removing them and saving the result in another string.</p><h2 id="61e0">Maketrans</h2><p id="5b9a">This method creates a mapping of Unicode ASCII codes of characters, in the shape of a <code>dictionary</code>. Remember <a href="https://readmedium.com/up-your-python-coding-skills-dictionaries-c54117235e48">dictionaries</a>?</p><p id="d675">We can give the method 1, 2, or even 3 arguments. If we’re supplying it with an argument, that argument needs to be a <code>dictionary</code> representing an actual mapping. If we’re giving it 2 arguments, as we’ll do in just a minute, they need to have the same length, to have the mapping work. <a href="https://www.programiz.com/python-programming/methods/string/maketrans">Here</a>’s more on this <code>string.maketrans()</code> method</p><div id="d99c"><pre><span class="hljs-comment"># construct the two strings</span> <span class="hljs-attr">my_first_string</span> = <span class="hljs-string">"abc"</span> <span class="hljs-attr">my_second_string</span> = <span class="hljs-string">"def"</span></pre></div><div id="a171"><pre><span class="hljs-comment"># make the translation dictionary</span> <span class="hljs-literal">result</span> = str.maketrans(my_first_string, my_second_string) print(<span class="hljs-literal">result</span>)</pre></div><div id="a986"><pre><span class="hljs-attr">Output:</span> {<span class="hljs-attr">97:</span> <span class="hljs-number">100</span>, <span class="hljs-attr">98:</span> <span class="hljs-number">101</span>, <span class="hljs-attr">99:</span> <span class="hljs-number">102</span>}</pre></div><p id="89e4">The mapping process has the ASCII codes of the characters from the first string as keys (a is 97, b is 98, c is 99) and the ASCII codes of the characters belonging to the second string (d is 100, e is 101, f is 102) as their corresponding values.</p><h2 id="5f58">Partition a string</h2><p id="ef70">Almost like <code>str.split()</code>, but not quite. Here’s why:</p><div id="155e"><pre><span class="hljs-comment"># a simple string</span> my_string = <span class="hljs-string">"abcbde"</span> <span class="hljs-literal">result</span> = my_string.partition(<span class="hljs-string">"b"</span>) print(<span class="hljs-literal">result</span>)</pre></div><div id="edc6"><pre># a <span class="hljs-built_in">second</span> <span class="hljs-built_in">string</span> my_other_string = <span class="hljs-string">"abc"</span> result = my_other_string.<span class="hljs-built_in">partition</span>(<span class="hljs-string">"d"</span>) <span class="hljs-built_in">print</span>(result)</pre></div><div id="6220"><pre><span class="hljs-comment"># an empty string</span> my_empty_string = <span class="hljs-string">""</span> <span class="hljs-literal">result</span> = my_empty_string.partition(<span class="hljs-string">","</span>) print(<span class="hljs-literal">result</span>)</pre></div><div id="bb5f"><pre><span class="hljs-keyword">Output</span>: (<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hl

Options

js-string">'cbde'</span>) (<span class="hljs-string">'abc'</span>, <span class="hljs-string">''</span>, <span class="hljs-string">''</span>) (<span class="hljs-string">''</span>, <span class="hljs-string">''</span>, <span class="hljs-string">''</span>)</pre></div><p id="b1ca">The method needs a separator character to partition the string by. The method only takes the first occurrence (if any) of the separator.</p><p id="f689">The method is returning a <code>tuple</code> (see <a href="https://readmedium.com/python-up-your-code-tuples-b28c57df7069">here</a> for more on tuples) of exactly 3 elements:</p><ul><li>if the separator has been found within the string, the tuple contains the leading substring, the separator, and the trailing substring;</li><li>if the separator doesn’t exist within the string, the tuple will contain the original string and two empty strings.</li></ul><h2 id="1f8c">Remove prefix</h2><p id="f2f9">Sometimes we just need a leading part of a string — the prefix — removed:</p><div id="1c4a"><pre><span class="hljs-comment"># regular string</span> my_string = <span class="hljs-string">"abc"</span> result = my_string.removeprefix(<span class="hljs-string">"a"</span>) print(f<span class="hljs-string">"|{result}|"</span>)</pre></div><div id="2bab"><pre># a <span class="hljs-built_in">second</span> <span class="hljs-built_in">example</span> - no <span class="hljs-built_in">prefix</span> to <span class="hljs-built_in">remove</span> my_other_string = <span class="hljs-string">"abc"</span> result = my_other_string.removeprefix(<span class="hljs-string">"d"</span>) <span class="hljs-built_in">print</span>(f<span class="hljs-string">"|{result}|"</span>)</pre></div><div id="821e"><pre><span class="hljs-comment"># a third example</span> my_third_string = <span class="hljs-string">"aabc"</span> result = my_third_string.removeprefix(<span class="hljs-string">"a"</span>) print(f<span class="hljs-string">"|{result}|"</span>)</pre></div><div id="9847"><pre><span class="hljs-comment"># an empty string</span> my_empty_string = <span class="hljs-string">""</span> result = my_empty_string.removeprefix(<span class="hljs-string">"a"</span>) print(f<span class="hljs-string">"|{result}|"</span>)</pre></div><div id="5ec4"><pre>Output: |<span class="hljs-string">bc</span>| |<span class="hljs-string">abc</span>| |<span class="hljs-string">abc</span>| ||</pre></div><p id="ea31">As can be clearly seen, this doesn’t affect subsequent occurrences of the same prefix. In other words, it does not behave recursively. For example, given <code>aabc</code> and the prefix to remove being <code>a</code>, the method only removes the first occurrence of the prefix.</p><p id="7119">Again, the pipe symbols are just there to help visualize the result on the fourth, empty string test.</p><h2 id="9a9a">Remove suffix</h2><p id="6acd">Same deal as <code>str.removeprefix()</code>, except that this time around it’s the suffix that gets eliminated. And, as we’ll see in just a sec, it doesn’t act in a recursive manner:</p><div id="d0b4"><pre><span class="hljs-comment"># first string</span> my_string = <span class="hljs-string">"abc"</span> result = my_string.removesuffix(<span class="hljs-string">"c"</span>) print(f<span class="hljs-string">"|{result}|"</span>)</pre></div><div id="99a3"><pre># another <span class="hljs-built_in">string</span> - <span class="hljs-keyword">no</span> suffix <span class="hljs-keyword">to</span> <span class="hljs-built_in">remove</span> my_other_string = <span class="hljs-string">"abc"</span> result = my_other_string.removesuffix(<span class="hljs-string">"d"</span>) <span class="hljs-keyword">print</span>(<span class="hljs-keyword">f</span><span class="hljs-string">"|{result}|"</span>)</pre></div><div id="08ce"><pre><span class="hljs-comment"># a third example</span> my_third_string = <span class="hljs-string">"abcc"</span> result = my_third_string.removesuffix(<span class="hljs-string">"c"</span>) print(f<span class="hljs-string">"|{result}|"</span>)</pre></div><div id="5386"><pre>my_empty_string = <span class="hljs-string">""</span> result = my_empty_string<span class="hljs-selector-class">.removesuffix</span>(<span class="hljs-string">"c"</span>) <span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(f<span class="hljs-string">"|{result}|"</span>)</span></span></pre></div><div id="c844"><pre>Output: |<span class="hljs-string">ab</span>| |<span class="hljs-string">abc</span>| |<span class="hljs-string">abc</span>| ||</pre></div><h2 id="cca0">Replace substring</h2><p id="4d3a">Easily one of the most widely used string methods (and not just in Python), string replacing is very straightforward: it seeks out any occurrences of one substring and replaces all of those with another, secondary substring that we specify. It can work as a substring eliminator too if the second substring we feed into the method is an empty string:</p><div id="1347"><pre>my_string = <span class="hljs-string">"abc"</span> result = my_string<span class="hljs-selector-class">.replace</span>(<span class="hljs-string">"b"</span>, <span class="hljs-string">"d"</span>) <span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(result)</span></span></pre></div><div id="679f"><pre>my_other_string = <span class="hljs-string">"abc"</span> result = my_other_string<span class="hljs-selector-class">.replace</span>(<span class="hljs-string">"d"</span>, <span class="hljs-string">"e"</span>) <span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(result)</span></span></pre></div><div id="ffbe"><pre>my_third_string = <span class="hljs-string">"abc"</span> result = my_third_string<span class="hljs-selector-class">.replace</span>(<span class="hljs-string">"b"</span>, <span class="hljs-string">""</span>) <span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(result)</span></span></pre></div><div id="41fd"><pre><span class="hljs-symbol">Output:</span> <span class="hljs-keyword">adc</span> abc ac</pre></div><h2 id="d287">Return rightmost occurrence of substring (rfind)</h2><p id="fe7c">Very straightforward, this returns the rightmost (you could say the last) occurrence of a substring within a string, or <code>-1</code> if it fails to find it. We can also give it the optional <code>start</code> and <code>end</code> arguments, so we don’t always need to search the entire string.</p><div id="d832"><pre><span class="hljs-comment"># find rightmost occurrence of "b" in "abcba"</span> my_string = <span class="hljs-string">"abcba"</span> <span class="hljs-literal">result</span> = my_string.rfind(<span class="hljs-string">"b"</span>) print(<span class="hljs-literal">result</span>)</pre></div><div id="8e02"><pre><span class="hljs-comment"># "d" doesn't exist in "abcba"</span> my_other_string = <span class="hljs-string">"abcba"</span> <span class="hljs-literal">result</span> = my_other_string.rfind(<span class="hljs-string">"d"</span>) print(<span class="hljs-literal">result</span>)</pre></div><div id="3aac"><pre><span class="hljs-attribute">Output</span>: 3 <span class="hljs-literal">-</span>1</pre></div><h2 id="8154">Return rightmost occurrence of substring (rindex)</h2><p id="28ed">Same deal as with <code>str.rfind()</code>, we can even supply it with <code>start</code> and <code>end</code> optional arguments, but we’ll get an exception thrown if the search failed, as opposed to <code>-1</code> getting returned in such a case:</p><div id="6fb8"><pre><span class="hljs-comment"># find rightmost occurrence of "b" in "abcba"</span> my_string = <span class="hljs-string">"abcba"</span> <span class="hljs-literal">result</span> = my_string.rindex(<span class="hljs-string">"b"</span>) print(<span class="hljs-literal">result</span>)</pre></div><div id="7de3"><pre><span class="hljs-attr">my_other_string</span> = <span class="hljs-string">"abcba"</span> <span class="hljs-attr">result</span> = my_other_string.rindex(<span class="hljs-string">"d"</span>)</pre></div><div id="ecc5"><pre><span class="hljs-symbol">Output:</span> <span class="hljs-number">3</span> Traceback (most recent <span class="hljs-keyword">call</span> last): ... result = my_other_string.rindex(<span class="hljs-string">"d"</span>) <span class="hljs-symbol">ValueError:</span> substring not found</pre></div><h2 id="b63b">Right justify a string</h2><p id="fa5d">Like <code>str.ljust()</code>, except the justifying process is being done on the right side of the width:</p><div id="02f1"><pre><span class="hljs-comment"># a regular string</span> my_string = <span class="hljs-string">"Abc"</span> <span class="hljs-literal">result</span> = my_string.rjust(<span class="hljs-number">10</span>, <span class="hljs-string">"."</span>) print(<span class="hljs-literal">result</span>)</pre></div><div id="f274"><pre><span class="hljs-comment"># an empty string</span> my_empty_string = <span class="hljs-string">""</span> <span class="hljs-literal">result</span> = my_empty_string.rjust(<span class="hljs-number">10</span>, <span class="hljs-string">"."</span>) print(<span class="hljs-literal">result</span>)</pre></div><div id="2d7a"><pre>Output: <span class="hljs-params">...</span><span class="hljs-params">...</span>.Abc <span class="hljs-params">...</span><span class="hljs-params">...</span><span class="hljs-params">...</span>.</pre></div><h2 id="b081">Right partitioning a string</h2><p id="f01d">Like <code>str.partition()</code>, except on the right side, meaning the search process is starting at the end:</p><div id="8783"><pre><span class="hljs-comment"># a simple string</span> my_string = <span class="hljs-string">"abcbde"</span> <span class="hljs-literal">result</span> = my_string.rpartition(<span class="hljs-string">"b"</span>) print(<span class="hljs-literal">result</span>)</pre></div><div id="aab1"><pre><span class="hljs-comment"># a second string</span> my_other_string = <span class="hljs-string">"abc"</span> <span class="hljs-literal">result</span> = my_other_string.rpartition(<span class="hljs-string">"d"</span>) print(<span class="hljs-literal">result</span>)</pre></div><div id="199d"><pre><span class="hljs-comment"># an empty string</span> my_empty_string = <span class="hljs-string">""</span> <span class="hljs-literal">result</span> = my_empty_string.rpartition(<span class="hljs-string">","</span>) print(<span class="hljs-literal">result</span>)</pre></div><div id="3de9"><pre><span class="hljs-keyword">Output</span>: (<span class="hljs-string">'abc'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'de'</span>) (<span class="hljs-string">''</span>, <span class="hljs-string">''</span>, <span class="hljs-string">'abc'</span>) (<span class="hljs-string">''</span>, <span class="hljs-string">''</span>, <span class="hljs-string">''</span>)</pre></div><h2 id="003a">Right splitting a string</h2><p id="0752">This method effectively splits a string into a tuple of substrings by a specified delimiter-string. The search is being done starting from the right and working its way up to the left:</p><div id="fb04"><pre><span class="hljs-comment"># first example</span> my_string = <span class="hljs-string">"Abc"</span> <span class="hljs-literal">result</span> = my_string.rsplit(<span class="hljs-string">"b"</span>) print(<span class="hljs-literal">result</span>)</pre></div><div id="81b9"><pre><span class="hljs-comment"># non-existent delimiter</span> my_other_string = <span class="hljs-string">"Abc"</span> <span class="hljs-literal">result</span> = my_string.rsplit(<span class="hljs-string">"d"</span>) print(<span class="hljs-literal">result</span>)</pre></div><div id="9d1b"><pre><span class="hljs-comment"># empty string</span> my_empty_string = <span class="hljs-string">""</span> <span class="hljs-literal">result</span> = my_empty_string.rsplit(<span class="hljs-string">"b"</span>) print(<span class="hljs-literal">result</span>)</pre></div><div id="5b5a"><pre><span class="hljs-symbol">Output</span>: [<span class="hljs-string">'A'</span>, <span class="hljs-string">'c'</span>] [<span class="hljs-string">'Abc'</span>] [<span class="hljs-string">''</span>]</pre></div><h2 id="6cff">Strip trailing whitespace</h2><p id="f1be">This is purely similar to <code>str.lstrip()</code>, that was effectively stripping out any leading whitespace characters (spaces, tabs, etc.), the sole difference being that this <code>str.rstrip()</code> is taking care of the trailing (rightmost) part:</p><div id="865c"><pre><span class="hljs-comment"># regular string, leading and trailing whitespace</span> my_string = <span class="hljs-string">" Abc Def \t"</span> <span class="hljs-built_in">print</span>(<span class="hljs-string">f"|<span class="hljs-subst">{my_string}</span>|"</span>)</pre></div><div id="2e85"><pre><span class="hljs-comment"># strip away the trailing whitespace</span> result = my_string.rstrip() <span class="hljs-built_in">print</span>(<span class="hljs-string">f"|<span class="hljs-subst">{result}</span>|"</span>)</pre></div><div id="34ad"><pre><span class="hljs-comment"># empty string</span> my_empty_string = <span class="hljs-string">""</span> result = my_empty_string.rstrip() print(f<span class="hljs-string">"|{result}|"</span>)</pre></div><div id="3440"><pre>Output: |<span class="hljs-string"> Abc Def </span>| |<span class="hljs-string"> Abc Def</span>| ||</pre></div><h2 id="3d37">Splitting a string</h2><p id="d772">Entirely similar to <code>str.rsplit()</code> we showcased earlier, except for the fact that the search process begins at the left (starting) side, all the way to the right (ending) side of the string:</p><div id="28a3"><pre><span class="hljs-variable">my_string</span> = <span class="hljs-string">"Abc"</span> <span class="hljs-variable"><span class="hljs-class">result</span></span> = <span class="hljs-variable">my_string.split</span>(<span class="hljs-string">"b"</span>) <span class="hljs-function"><span class="hljs-title">print</span>(<span class="hljs-variable"><span class="hljs-class">result</span></span>)</span></pre></div><div id="00c6"><pre><span class="hljs-variable">my_other_string</span> = <span class="hljs-string">"Abc"</span> <span class="hljs-variable"><span class="hljs-class">result</span></span> = <span class="hljs-variable">my_string.split</span>(<span class="hljs-string">"d"</span>) <span class="hljs-function"><span class="hljs-title">print</span>(<span class="hljs-variable"><span class="hljs-class">result</span></span>)</span></pre></div><div id="e936"><pre><span class="hljs-variable">my_empty_string</span> = <span class="hljs-string">""</span> <span class="hljs-variable"><span class="hljs-class">result</span></span> = <span class="hljs-variable">my_empty_string.split</span>(<span class="hljs-string">"b"</span>) <span class="hljs-function"><span class="hljs-title">print</span>(<span class="hljs-variable"><span class="hljs-class">result</span></span>)</span></pre></div><div id="7be7"><pre><span class="hljs-symbol">Output</span>: [<span class="hljs-string">'A'</span>, <span class="hljs-string">'c'</span>] [<span class="hljs-string">'Abc'</span>] [<span class="hljs-string">''</span>]</pre></div><h2 id="df05">Splitting multiline strings</h2><p id="0c0f">We can even turn a multiline string into a list of strings, using <code>str.splitlines()</code>:</p><div id="eb81"><pre><span class="hljs-variable">my_string</span> = <span class="hljs-string">"Abc\nDef"</span> <span class="hljs-variable"><span class="hljs-class">result</span></span> = <span class="hljs-variable">my_string.splitlines</span>() <span class="hljs-function"><span class="hljs-title">print</span>(<span class="hljs-variable"><span class="hljs-class">result</span></span>)</span></pre></div><div id="28a6"><pre><span class="hljs-symbol">Output</span>: [<span class="hljs-string">'Abc'</span>, <span class="hljs-string">'Def'</span>]</pre></div><h2 id="f2ca">String starts with</h2><p id="b776">Just as we have covered the <code>str.endswith()</code> method, so shall we demo the similar <code>str.startswith()</code> method:</p><div id="67c7"><pre>my_string = <span class="hljs-string">"Abc"</span> <span class="hljs-built_in">print</span>(<span class="hljs-string">f"<span class="hljs-subst">{<span class="hljs-built_in">id</span>(my_string)}</span>: <span class="hljs-subst">{my_string}</span>"</span>)</pre></div><div id="a23c"><pre>result = my_string<span class="hljs-selector-class">.startswith</span>(<span class="hljs-string">"Ab"</span>) <span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(f<span class="hljs-string">"{result}"</span>)</span></span></pre></div><div id="1b93"><pre><span class="hljs-attr">Output:</span> <span class="hljs-attr">139690571077232:</span> <span class="hljs-string">Abc</span> <span class="hljs-literal">True</span></pre></div><h2 id="340e">Strip leading and trailing whitespace</h2><p id="0c76">Combining the effects of both <code>str.rstrip()</code> and <code>str.lstrip()</code> methods, <code>str.strip()</code> effectively removes all leading and trailing whitespace characters (tabs, spaces, etc.):</p><div id="0df5"><pre>my_string = <span class="hljs-string">" \t Abc Def \t"</span> <span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(f<span class="hljs-string">"|{my_string}|"</span>)</span></span></pre></div><div id="dfb8"><pre>result = my_string<span class="hljs-selector-class">.strip</span>() <span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(f<span class="hljs-string">"|{result}|"</span>)</span></span></pre></div><div id="379e"><pre>my_empty_string = <span class="hljs-string">""</span> result = my_empty_string<span class="hljs-selector-class">.strip</span>() <span class="hljs-function"><span class="hljs-title">print</span><span class="hljs-params">(f<span class="hljs-string">"|{result}|"</span>)</span></span></pre></div><div id="dab0"><pre>Output: |<span class="hljs-string"> Abc Def </span>| |<span class="hljs-string">Abc Def</span>| ||</pre></div><h2 id="8495">Swapping uppercase with lowercase and vice-versa</h2><p id="aace">Sometimes we may be required to swap the case for all of the characters in a string:</p><div id="3d24"><pre><span class="hljs-variable">my_string</span> = <span class="hljs-string">"Abc Def"</span> <span class="hljs-variable"><span class="hljs-class">result</span></span> = <span class="hljs-variable">my_string.swapcase</span>() <span class="hljs-function"><span class="hljs-title">print</span>(<span class="hljs-variable"><span class="hljs-class">result</span></span>)</span></pre></div><div id="fe6a"><pre><span class="hljs-symbol">Output:</span> aBC dEF</pre></div><h2 id="eaec">Convert a string to titlecase</h2><p id="64ff">As its name suggests, <code>str.title()</code> is effectively going to ensure that only the first letter of every word in the string gets capitalized:</p><div id="5fbe"><pre><span class="hljs-variable">my_string</span> = <span class="hljs-string">"abc def"</span> <span class="hljs-variable"><span class="hljs-class">result</span></span> = <span class="hljs-variable">my_string.title</span>() <span class="hljs-function"><span class="hljs-title">print</span>(<span class="hljs-variable"><span class="hljs-class">result</span></span>)</span></pre></div><div id="b74c"><pre><span class="hljs-symbol">Output:</span> Abc Def</pre></div><h2 id="4712">Translate string</h2><p id="f311">Using a table of translations (using <code>str.maketrans()</code> we discussed earlier), we can easily translate a string into another:</p><div id="7d36"><pre><span class="hljs-comment"># create translation table</span> <span class="hljs-attr">keys</span> = <span class="hljs-string">"abc"</span> <span class="hljs-attr">values</span> = <span class="hljs-string">"def"</span> <span class="hljs-attr">table</span> = str.maketrans(keys, values)</pre></div><div id="071a"><pre># <span class="hljs-built_in">translate</span> a <span class="hljs-built_in">string</span> my_string = <span class="hljs-string">"cba"</span> result = my_string.<span class="hljs-built_in">translate</span>(table) <span class="hljs-built_in">print</span>(result)</pre></div><div id="fccf"><pre><span class="hljs-symbol">Output:</span> fed</pre></div><h2 id="6ccf">Convert a string to uppercase</h2><p id="2c16">All characters of a string will get turned to uppercase:</p><div id="afc0"><pre><span class="hljs-variable">my_string</span> = <span class="hljs-string">"abc"</span> <span class="hljs-variable"><span class="hljs-class">result</span></span> = <span class="hljs-variable">my_string.upper</span>() <span class="hljs-function"><span class="hljs-title">print</span>(<span class="hljs-variable"><span class="hljs-class">result</span></span>)</span></pre></div><div id="b11b"><pre><span class="hljs-symbol">Output:</span> ABC</pre></div><h2 id="d27d">Add leading zeroes to a string</h2><p id="85c5">Very straightforward, this will add as many leading zeroes as needed to fulfill the length argument:</p><div id="7359"><pre><span class="hljs-variable">my_string</span> = <span class="hljs-string">"123"</span> <span class="hljs-variable"><span class="hljs-class">result</span></span> = <span class="hljs-variable">my_string.zfill</span>(<span class="hljs-number">2</span>) <span class="hljs-function"><span class="hljs-title">print</span>(<span class="hljs-variable"><span class="hljs-class">result</span></span>)</span></pre></div><div id="f48a"><pre><span class="hljs-variable">my_other_string</span> = <span class="hljs-string">"123"</span>
<span class="hljs-variable"><span class="hljs-class">result</span></span> = <span class="hljs-variable">my_other_string.zfill</span>(<span class="hljs-number">8</span>) <span class="hljs-function"><span class="hljs-title">print</span>(<span class="hljs-variable"><span class="hljs-class">result</span></span>)</span></pre></div><div id="ea3f"><pre><span class="hljs-symbol">Output:</span> <span class="hljs-number">123</span> <span class="hljs-number">00000123</span></pre></div><p id="a700">Quite the long article on strings. In Python and pretty much anywhere else, strings really are a big deal. We so very rarely need to memorize anything, but we must absolutely learn one thing: where to look for the correct information. This article only served as a very quick demo of string methods we can use on Python string objects, but the learning process should by no means end here. The Internet is full of actual knowledge goldmines and what better place to start looking than the <a href="https://docs.python.org/3/library/string.html">official</a> docs pages?</p><p id="0aa7">Keep learning, keep getting better at what you do, and most importantly: stay safe and happy coding! I’ll see you at the <a href="https://readmedium.com/python-up-your-code-list-comprehensions-bc34ac300b48">next</a> one!</p><p id="362c"><i>More content at<b> <a href="https://plainenglish.io/">PlainEnglish.io</a></b>. Sign up for our<b> <a href="http://newsletter.plainenglish.io/">free weekly newsletter</a></b>. Follow us on <a href="https://twitter.com/inPlainEngHQ"><b>Twitter</b></a> and <a href="https://www.linkedin.com/company/inplainenglish/"><b>LinkedIn</b></a>. Check out our <a href="https://discord.gg/GtDtUAvyhW"><b>Community Discord</b></a> and join our <a href="https://inplainenglish.pallet.com/talent/welcome"><b>Talent Collective</b></a>.</i></p></article></body>

Up Your Coding Skills with Python: Strings

Part 2: Showcasing some of the most widely used methods applied to string objects in Python

Photo by Shubham Dhage on Unsplash

As the natural follow-up to this article, where I’ve only just scratched the surface of what Python string objects are, I’ll now be doing a general overview of some of the most widely used methods associated with the usage and manipulation of string objects in Python. Going through each of them, one by one, this article aims to familiarize and maybe even point out some hints about Python strings.

Capitalize a string

Useful for situations where you need to ensure that some string is always capitalized (starts with an uppercase letter):

# construct the string
my_string = "abc def"
print(f"{id(my_string)}: {my_string}")
# capitalize and save into a new string
my_second_string = my_string.capitalize()
print(f"{id(my_second_string)}: {my_second_string}")
Output:
139753899857840: abc def
139753900121200: Abc def

Notice how only the first letter of the string was converted to uppercase.

Casefolding a string

Casefolding in Python is an operation that, like the string.lower(), ensures all characters are converted to lowercase. The difference between string.lower() and this string.casefold() is that while lower() handles only characters in the ASCII range, casefold() goes beyond this range, ensuring many other unicode characters get — shall we call it — normalized in view of string comparisons. Since there are languages that feature characters outside of the regular 26-letter alphabet, this string.casefold() is sure to help when trying to compare those strings. For languages featuring all characters within the ASCII range, there should be no difference between casefold() and lower():

# construct the string
my_string = "ABc"
print(f"{id(my_string)}: {my_string}")
# casefold and save into a second string
my_second_string = my_string.casefold()
print(f"{id(my_second_string)}: {my_second_string}")
Output:
140000165189552: ABc
140000165452912: abc

Center aligning a string

Not as often used as there’s also the string.format() that would be capable of achieving the same effect and more, for that matter, but still worth mentioning, this string.center() method is a quick and intuitive way of centering a string within a given character length:

# construct the string
my_string = "Abc"
print(f"{id(my_string)}: |{my_string}|")
# center it, then save it into another string
my_second_string = my_string.center(10)
print(f"{id(my_second_string)}: |{my_second_string}|")
Output:
139866075272816: |Abc|
139866075536176: |   Abc    |

As you can see, the string has been successfully centered. I used pipe characters in the print() statements to further emphasize the centering effect.

Counting substring occurrences

Say we have a string on our hands. One that contains a substring in repetition. How do we get the number of its occurrences? By using string.count():

# construct the string
my_string = "ABaca"
print(f"{id(my_string)}: {my_string}")
# substring to count
substring = "a"
# count the substring occurrences
no_of_chars = my_string.count(substring)
print(f"{my_string} has {no_of_chars} occurrences of '{substring}'")
Output:
140705430460336: ABaca
ABaca has 2 occurrences of 'a'

Encoding a string

The string.encode() method ensures we get an encoded version of the string we have. We can give it two parameters: the type of encoding we want done and the response type in case of encoding failure. You can read more about it here.

# construct the string
my_string = "Abc"
print(f"{id(my_string)}: {my_string}")
# encode the string in utf-8
my_byte_string = my_string.encode(encoding="UTF-8")
print(f"{id(my_byte_string)}: {my_byte_string}")
Output:
139704333342640: Abc
139704334105600: b'Abc'

Notice the b in front of the encoded strings? That’s the telltale sign of a bytes string. Regular string gets encoded and this result is of type bytes.

Check if a string ends with a substring

This is a very straightforward operation. Just apply string.endswith() and enjoy the boolean result coming out of it:

# construct the string
my_string = "Abc"
print(f"{id(my_string)}: {my_string}")
# does the string end with 'bc'?
result = my_string.endswith("bc")
print(f"{result}")
Output:
140090950047664: Abc
True

Expand tabs to spaces

Sometimes, a string can contain tabs. And sometimes, a requirement at work or otherwise is to have those tabs converted into spaces. This is where this method comes in handy. The string.expandtabs() method is successfully transforming the string, converting every tab character it finds into a number of space characters, according to the tab size argument you’re supplying the method with.

Also, it is very important to note that it does actually keep track of the current cursor position. If the string is, say, Abc\tdef the cursor position is at, say, 3 — because this is where the tab character sits at — and we have the tab size argument as 8, then this will result in an extra set of 5 spaces being added to the string instead of the tab character.

# construct the string
my_string = "Abc\tdef"
print(f"{id(my_string)}: {my_string}")
# expand the tabs into spaces
my_second_string = my_string.expandtabs(3)
print(f"{id(my_second_string)}: {my_second_string}")
my_third_string = my_string.expandtabs()
print(f"{id(my_third_string)}: {my_third_string}")
Output:
139624277039024: Abc    def
139624277302384: Abc   def
140087303330992: Abc     def

Find substring within a string

Again, very straightforward. We just need to use string.find() and it will return the index of the first occurrence of the substring within our searched string, or -1, should it fail to find it:

# construct the string
my_string = "Abc"
print(f"{id(my_string)}: {my_string}")
# look for the substring
substring = "b"
index = my_string.find("b")
print(f"{index}")
# look for a nonexistent substring
index = my_string.find("d")
print(f"{index}")
Output:
140410169481136: Abc
1
-1

String formatting

One of the most (if probably not the most) widely used string methods in Python is string.format(), as it allows for a multitude of features, such as left/right/center alignment, the number of decimals, and the total number of digits, hex or octal representations in the case of numbers, positional formatting, variable substitution formatting, and so on.

Quite frankly, string formatting would be deserving of a dedicated article, it’s that versatile. For now, I’m only considering covering the essentials, even if that means barely scratching the surface. More stuff about string formatting than I could possibly share in a small article like this can be found here.

# basic string formatting
my_string = "Today is {}"
print(f"{id(my_string)}: {my_string}")
my_second_string = my_string.format("Monday")
print(f"{id(my_second_string)}: {my_second_string}")
# right alignment formatting
my_string = "Right aligned: {0:>20}.".format("Hello, world!")
print(f"{id(my_string)}: {my_string}")
# left alignment formatting
my_string = "Left aligned: {0:<20}.".format("Hello, world!")
print(f"{id(my_string)}: {my_string}")
# center alignment formatting
my_string = "Center aligned: {0:^20}.".format("Hello, world!")
print(f"{id(my_string)}: {my_string}")
# hex formatting
my_string = "{0} is {0:x} in hex".format(65)
print(f"{id(my_string)}: {my_string}")
# octal formatting
my_string = "{0} is {0:o} in oct".format(65)
print(f"{id(my_string)}: {my_string}")
# pi as 5 decimals
my_string = "{0}: {1:7.5f}".format("Pi", 3.1415926535)
print(f"{id(my_string)}: {my_string}")
# pi as 4 decimals and variable substitution
my_string = "{name}: {val:6.4f}".format(val=3.1415926535, name="Pi")
print(f"{id(my_string)}: {my_string}")
# pi as 4 decimals and dictionary unpacking
values = {"value": 3.1415926535, "name": "Pi"}
my_string = "{name}: {value:6.4f}".format(**values)
print(f"{id(my_string)}: {my_string}")
# pi as 4 decimals and format_map()
values = {"value": 3.1415926535, "name": "Pi"}
my_string = "{name}: {value:6.4f}".format_map(values)
print(f"{id(my_string)}: {my_string}")
Output:
140259719878576: Today is {}
140259720144432: Today is Monday
140259720001552: Right aligned:        Hello, world!.
140259720001744: Left aligned: Hello, world!       .
140259720001552: Center aligned:    Hello, world!    .
140259720145520: 65 is 41 in hex
140259720082208: 65 is 101 in oct
140259720145520: Pi: 3.14159
140259720145584: Pi: 3.1416
140259720145520: Pi: 3.1416
140259720145584: Pi: 3.1416

Substring index

Sometimes we’re interested to see where has a substring firstly occurred in a string. We could simply use string.find() for that, right? Well, it depends. If we want it to return -1 in case of failure, then yes. But if we’re counting on an exception being thrown in case the substring isn’t found, then we’re better off using string.index():

# construct the string
my_string = "Abcb"
# find index of 'b'
index = my_string.index("b")
print(f"{index}")
# try to find index of 'd'
index = my_string.index("d")
1
Traceback (most recent call last):
  ...
    index = my_string.index("d")
ValueError: substring not found

We tried to find d in Abcb. Since it obviously didn’t find d anywhere in that string, it raised a ValueError exception for us to catch and do something with it.

Alpha-numeric string

Sometimes we need to check if all characters in a given string are alpha-numeric (they’re only letters and numbers):

# alpha-numeric string
my_string = "Abc123"
result = my_string.isalnum()
print(result)
# non-alpha-numeric string
my_second_string = "Abc.123"
result = my_second_string.isalnum()
print(result)
# empty string
my_empty_string = ""
result = my_empty_string.isalnum()
print(result)
Output:
True
False
False

Alpha string

Other times, we’re aiming to test if the string is only consisting of alphabet characters (only letters):

# alphabet string
my_string = "Abc"
result = my_string.isalpha()
print(result)
# non-alphabet string
my_second_string = "Ab."
result = my_second_string.isalpha()
print(result)
# empty string
my_empty_string = ""
result = my_empty_string.isalpha()
print(result)
Output:
True
False
False

ASCII string

In other words, we check if the string only contains characters in the current standard ASCII range or not:

# construct an ascii string
my_string = "Abc"
result = my_string.isascii()
print(result)
# empty string
my_empty_string = ""
result = my_empty_string.isascii()
print(result)
# non-ascii string
my_non_ascii_string = 'This is not an ascii string \u0080'
result = my_non_ascii_string.isascii()
print(result)
Output:
True
True
False

Decimal string

It may be that sometimes a requirement is that a string is composed of only decimal characters. To that end, string.isdecimal() is available for us. Let’s see how that works:

# construct a non-decimal string
my_string = "Abc"
result = my_string.isdecimal()
print(result)
# construct a decimal string
my_decimal_string = "123"
result = my_decimal_string.isdecimal()
print(result)
# construct a decimal string with a decimal point
my_other_string = "123.5"
result = my_other_string.isdecimal()
print(result)
# empty string
my_empty_string = ""
result = my_empty_string.isdecimal()
print(result)
# still a non-decimal string
my_non_decimal_string = "²3455"
result = my_non_decimal_string.isdecimal()
print(result)
Output:
False
True
False
False
False

It’s only decimal if every character is a decimal character. As we could see, superscript (exponent) characters or decimal points cause the check to fail, returning False.

Digit string

Similarly to string.isdecimal(), the string.isdigit() method checks if all characters are string representations of digits. Unlike string.isdecimal(), though, superscript (exponent) characters are considered digits:

# construct a non-digit string
my_string = "Abc"
result = my_string.isdigit()
print(result)
# empty string
my_empty_string = ""
result = my_empty_string.isdigit()
print(result)
# digit string
my_digit_string = "²3455"
result = my_digit_string.isdigit()
print(result)
# a roman numeral string
my_roman_string = "ↁ"
result = my_roman_string.isdigit()
print(result)
Output:
False
False
True
False

Test if string is a valid identifier

The string.isidentifier() method will check if it can be considered a valid identifier in Python. An identifier is considered valid in Python if it only contains alphabet characters (letters), numbers, and underscores. Furthermore, it cannot contain spaces and cannot start with a digit.

# valid identifier
my_string = "Abc"
result = my_string.isidentifier()
print(result)
# invalid identifier
my_other_string = "Abc def"
result = my_other_string.isidentifier()
print(result)
# also invalid identifier
another_string = "123def"
result = another_string.isidentifier()
print(result)
# empty string
my_empty_string = ""
result = my_empty_string.isidentifier()
print(result)
Output:
True
False
False
False

Lowercase string

To test if all characters in one given string are lowercase, just use string.islower():

# not lowercase
my_string = "Abc"
result = my_string.islower()
print(result)
# lowercase
my_second_string = "def"
result = my_second_string.islower()
print(result)
# empty string
my_empty_string = ""
result = my_empty_string.islower()
print(result)
Output:
False
True
False

Check if string is numeric

The string.isnumeric() method checks if all characters within the string are numeric. Very similar to the string.isdigit() method, except for the case of Roman numeral strings. This is the main difference between isnumeric() and isdigit(), as the former will return True in the case of a Roman numeral string, while the latter will return False:

# a non-numeric string
my_string = "Abc"
result = my_string.isnumeric()
print(result)
# yet another non-numeric string
my_second_string = "12a"
result = my_second_string.isnumeric()
print(result)
# a numeric string
my_numeric_string = "²3455"
result = my_numeric_string.isnumeric()
print(result)
# an empty string
my_empty_string = ""
result = my_empty_string.isnumeric()
print(result)
# a roman numeral string
my_roman_string = "ↁ"
result = my_roman_string.isnumeric()
print(result)
Output:
False
False
True
False
True

Printable strings

There is a way to check if all characters in a string are printable. Let’s demonstrate the string.isprintable() method:

# printable string
my_string = "Abc"
result = my_string.isprintable()
print(result)
# empty string
my_empty_string = ""
result = my_empty_string.isprintable()
print(result)
# non-printable string
my_non_printable_string = "\nDef"
result = my_non_printable_string.isprintable()
print(result)
Output:
True
True
False

Turns out, empty strings are printable :)

Space strings

If a string is only containing spaces or tabs, the string.isspace() method will come in handy:

# regular string
my_string = "Abc"
result = my_string.isspace()
print(result)
# empty string
my_empty_string = ""
result = my_empty_string.isspace()
print(result)
# contains spaces, but not only spaces
my_non_space_string = "De f"
result = my_non_space_string.isspace()
print(result)
# whitespace string
my_space_string = "\t"
result = my_space_string.isspace()
print(result)
# another whitespace string
my_other_space_string = "\t "
result = my_other_space_string.isspace()
print(result)
Output:
False
False
False
True
True

Titlecase string

A string is considered to be titlecase if the words that make it up are having their first letters capitalized:

# titlecase string
my_string = "Abc D Efg"
result = my_string.istitle()
print(result)
# not a titlecase string
my_other_string = "Abc def"
result = my_other_string.istitle()
print(result)
# an empty string
my_empty_string = ""
result = my_empty_string.istitle()
print(result)
Output:
True
False
False

String is all uppercase

The string class even has a method to check if the string object is exclusively composed of uppercase characters:

# not an uppercase string
my_string = "Abc"
result = my_string.isupper()
print(result)
# an uppercase string
my_other_string = "DEF234-78U"
result = my_other_string.isupper()
print(result)
# an empty string
my_empty_string = ""
result = my_empty_string.isupper()
print(result)
Output:
False
True
False

Note that the uppercase string we tested, DEF234-78U, has been judged as an actual uppercase string, even though it contains digits and other characters, like the dash symbol.

Join iterable elements into a string

In Python, we can have a list of elements joined into a string, using a separator string:

# define the separator string
my_string = ","
# construct the iterator
my_list = ["a", "b", "c"]
# join the iterator elements into a string
result = my_string.join(my_list)
# print the resulting string
print(result)
Output:
a,b,c

Left justify a string

Very straightforward, string.ljust() will do just what its name suggests. All it needs is the width of the space in relation to which the justifying takes place and an optional fill character to fill in the rest of the width space we just mentioned:

# a regular string
my_string = "Abc"
result = my_string.ljust(10, ".")
print(result)
# an empty string
my_empty_string = ""
result = my_empty_string.ljust(10, ".")
print(result)
Output:
Abc.......
..........

Turn all characters lowercase

Another simple, straightforward, and very useful method, string.lower() will make sure your string stays lowercase:

# a regular string
my_string = "Abc"
result = my_string.lower()
print(f"|{result}|")
# an empty string
my_empty_string = ""
result = my_empty_string.lower()
print(f"|{result}|")
Output:
|abc|
||

Had to use pipe symbols to emphasize the empty string result in the second test.

Strip leading whitespace

Eventually, you’ll stumble upon strings containing leading whitespace, like spaces or tabs. Python allows for a simple way of getting rid of the leading whitespace:

# construct the string
my_string = " \t Abc Def "
print(f"|{my_string}|")
# left-strip the whitespace
result = my_string.lstrip()
print(f"|{result}|")
# try the same with an empty string
my_empty_string = ""
result = my_empty_string.lstrip()
print(f"|{result}|")
Output:
|        Abc Def |
|Abc Def |
||

Note that the method did nothing to alter the trailing whitespace, nor the whitespace from between the two substrings. It only affected the leading whitespace characters, effectively removing them and saving the result in another string.

Maketrans

This method creates a mapping of Unicode ASCII codes of characters, in the shape of a dictionary. Remember dictionaries?

We can give the method 1, 2, or even 3 arguments. If we’re supplying it with an argument, that argument needs to be a dictionary representing an actual mapping. If we’re giving it 2 arguments, as we’ll do in just a minute, they need to have the same length, to have the mapping work. Here’s more on this string.maketrans() method

# construct the two strings
my_first_string = "abc"
my_second_string = "def"
# make the translation dictionary
result = str.maketrans(my_first_string, my_second_string)
print(result)
Output:
{97: 100, 98: 101, 99: 102}

The mapping process has the ASCII codes of the characters from the first string as keys (a is 97, b is 98, c is 99) and the ASCII codes of the characters belonging to the second string (d is 100, e is 101, f is 102) as their corresponding values.

Partition a string

Almost like str.split(), but not quite. Here’s why:

# a simple string
my_string = "abcbde"
result = my_string.partition("b")
print(result)
# a second string
my_other_string = "abc"
result = my_other_string.partition("d")
print(result)
# an empty string
my_empty_string = ""
result = my_empty_string.partition(",")
print(result)
Output:
('a', 'b', 'cbde')
('abc', '', '')
('', '', '')

The method needs a separator character to partition the string by. The method only takes the first occurrence (if any) of the separator.

The method is returning a tuple (see here for more on tuples) of exactly 3 elements:

  • if the separator has been found within the string, the tuple contains the leading substring, the separator, and the trailing substring;
  • if the separator doesn’t exist within the string, the tuple will contain the original string and two empty strings.

Remove prefix

Sometimes we just need a leading part of a string — the prefix — removed:

# regular string
my_string = "abc"
result = my_string.removeprefix("a")
print(f"|{result}|")
# a second example - no prefix to remove
my_other_string = "abc"
result = my_other_string.removeprefix("d")
print(f"|{result}|")
# a third example
my_third_string = "aabc"
result = my_third_string.removeprefix("a")
print(f"|{result}|")
# an empty string
my_empty_string = ""
result = my_empty_string.removeprefix("a")
print(f"|{result}|")
Output:
|bc|
|abc|
|abc|
||

As can be clearly seen, this doesn’t affect subsequent occurrences of the same prefix. In other words, it does not behave recursively. For example, given aabc and the prefix to remove being a, the method only removes the first occurrence of the prefix.

Again, the pipe symbols are just there to help visualize the result on the fourth, empty string test.

Remove suffix

Same deal as str.removeprefix(), except that this time around it’s the suffix that gets eliminated. And, as we’ll see in just a sec, it doesn’t act in a recursive manner:

# first string
my_string = "abc"
result = my_string.removesuffix("c")
print(f"|{result}|")
# another string - no suffix to remove
my_other_string = "abc"
result = my_other_string.removesuffix("d")
print(f"|{result}|")
# a third example
my_third_string = "abcc"
result = my_third_string.removesuffix("c")
print(f"|{result}|")
my_empty_string = ""
result = my_empty_string.removesuffix("c")
print(f"|{result}|")
Output:
|ab|
|abc|
|abc|
||

Replace substring

Easily one of the most widely used string methods (and not just in Python), string replacing is very straightforward: it seeks out any occurrences of one substring and replaces all of those with another, secondary substring that we specify. It can work as a substring eliminator too if the second substring we feed into the method is an empty string:

my_string = "abc"
result = my_string.replace("b", "d")
print(result)
my_other_string = "abc"
result = my_other_string.replace("d", "e")
print(result)
my_third_string = "abc"
result = my_third_string.replace("b", "")
print(result)
Output:
adc
abc
ac

Return rightmost occurrence of substring (rfind)

Very straightforward, this returns the rightmost (you could say the last) occurrence of a substring within a string, or -1 if it fails to find it. We can also give it the optional start and end arguments, so we don’t always need to search the entire string.

# find rightmost occurrence of "b" in "abcba"
my_string = "abcba"
result = my_string.rfind("b")
print(result)
# "d" doesn't exist in "abcba"
my_other_string = "abcba"
result = my_other_string.rfind("d")
print(result)
Output:
3
-1

Return rightmost occurrence of substring (rindex)

Same deal as with str.rfind(), we can even supply it with start and end optional arguments, but we’ll get an exception thrown if the search failed, as opposed to -1 getting returned in such a case:

# find rightmost occurrence of "b" in "abcba"
my_string = "abcba"
result = my_string.rindex("b")
print(result)
my_other_string = "abcba"
result = my_other_string.rindex("d")
Output:
3
Traceback (most recent call last):
  ...
    result = my_other_string.rindex("d")
ValueError: substring not found

Right justify a string

Like str.ljust(), except the justifying process is being done on the right side of the width:

# a regular string
my_string = "Abc"
result = my_string.rjust(10, ".")
print(result)
# an empty string
my_empty_string = ""
result = my_empty_string.rjust(10, ".")
print(result)
Output:
.......Abc
..........

Right partitioning a string

Like str.partition(), except on the right side, meaning the search process is starting at the end:

# a simple string
my_string = "abcbde"
result = my_string.rpartition("b")
print(result)
# a second string
my_other_string = "abc"
result = my_other_string.rpartition("d")
print(result)
# an empty string
my_empty_string = ""
result = my_empty_string.rpartition(",")
print(result)
Output:
('abc', 'b', 'de')
('', '', 'abc')
('', '', '')

Right splitting a string

This method effectively splits a string into a tuple of substrings by a specified delimiter-string. The search is being done starting from the right and working its way up to the left:

# first example
my_string = "Abc"
result = my_string.rsplit("b")
print(result)
# non-existent delimiter
my_other_string = "Abc"
result = my_string.rsplit("d")
print(result)
# empty string
my_empty_string = ""
result = my_empty_string.rsplit("b")
print(result)
Output:
['A', 'c']
['Abc']
['']

Strip trailing whitespace

This is purely similar to str.lstrip(), that was effectively stripping out any leading whitespace characters (spaces, tabs, etc.), the sole difference being that this str.rstrip() is taking care of the trailing (rightmost) part:

# regular string, leading and trailing whitespace
my_string = " Abc Def \t"
print(f"|{my_string}|")
# strip away the trailing whitespace
result = my_string.rstrip()
print(f"|{result}|")
# empty string
my_empty_string = ""
result = my_empty_string.rstrip()
print(f"|{result}|")
Output:
| Abc Def       |
| Abc Def|
||

Splitting a string

Entirely similar to str.rsplit() we showcased earlier, except for the fact that the search process begins at the left (starting) side, all the way to the right (ending) side of the string:

my_string = "Abc"
result = my_string.split("b")
print(result)
my_other_string = "Abc"
result = my_string.split("d")
print(result)
my_empty_string = ""
result = my_empty_string.split("b")
print(result)
Output:
['A', 'c']
['Abc']
['']

Splitting multiline strings

We can even turn a multiline string into a list of strings, using str.splitlines():

my_string = "Abc\nDef"
result = my_string.splitlines()
print(result)
Output:
['Abc', 'Def']

String starts with

Just as we have covered the str.endswith() method, so shall we demo the similar str.startswith() method:

my_string = "Abc"
print(f"{id(my_string)}: {my_string}")
result = my_string.startswith("Ab")
print(f"{result}")
Output:
139690571077232: Abc
True

Strip leading and trailing whitespace

Combining the effects of both str.rstrip() and str.lstrip() methods, str.strip() effectively removes all leading and trailing whitespace characters (tabs, spaces, etc.):

my_string = " \t Abc Def \t"
print(f"|{my_string}|")
result = my_string.strip()
print(f"|{result}|")
my_empty_string = ""
result = my_empty_string.strip()
print(f"|{result}|")
Output:
|        Abc Def        |
|Abc Def|
||

Swapping uppercase with lowercase and vice-versa

Sometimes we may be required to swap the case for all of the characters in a string:

my_string = "Abc Def"
result = my_string.swapcase()
print(result)
Output:
aBC dEF

Convert a string to titlecase

As its name suggests, str.title() is effectively going to ensure that only the first letter of every word in the string gets capitalized:

my_string = "abc def"
result = my_string.title()
print(result)
Output:
Abc Def

Translate string

Using a table of translations (using str.maketrans() we discussed earlier), we can easily translate a string into another:

# create translation table
keys = "abc"
values = "def"
table = str.maketrans(keys, values)
# translate a string
my_string = "cba"
result = my_string.translate(table)
print(result)
Output:
fed

Convert a string to uppercase

All characters of a string will get turned to uppercase:

my_string = "abc"
result = my_string.upper()
print(result)
Output:
ABC

Add leading zeroes to a string

Very straightforward, this will add as many leading zeroes as needed to fulfill the length argument:

my_string = "123"
result = my_string.zfill(2)
print(result)
my_other_string = "123"\
result = my_other_string.zfill(8)
print(result)
Output:
123
00000123

Quite the long article on strings. In Python and pretty much anywhere else, strings really are a big deal. We so very rarely need to memorize anything, but we must absolutely learn one thing: where to look for the correct information. This article only served as a very quick demo of string methods we can use on Python string objects, but the learning process should by no means end here. The Internet is full of actual knowledge goldmines and what better place to start looking than the official docs pages?

Keep learning, keep getting better at what you do, and most importantly: stay safe and happy coding! I’ll see you at the next one!

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter and LinkedIn. Check out our Community Discord and join our Talent Collective.

Python
Programming
Coding
Tutorial
String
Recommended from ReadMedium