[Tut] Python | Split String into Characters - Printable Version +- Sick Gaming (https://www.sickgaming.net) +-- Forum: Programming (https://www.sickgaming.net/forum-76.html) +--- Forum: Python (https://www.sickgaming.net/forum-83.html) +--- Thread: [Tut] Python | Split String into Characters (/thread-100125.html) |
[Tut] Python | Split String into Characters - xSicKxBot - 10-22-2022 Python | Split String into Characters <div> <div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload="{"align":"left","id":"815773","slug":"default","valign":"top","ignore":"","reference":"auto","class":"","count":"0","readonly":"","score":"0","best":"5","gap":"5","greet":"Rate this post","legend":"0\/5 - (0 votes)","size":"24","width":"0","_legend":"{score}\/{best} - ({count} {votes})","font_factor":"1.25"}"> <div class="kksr-stars"> <div class="kksr-stars-inactive"> <div class="kksr-star" data-star="1" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="2" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="3" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="4" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" data-star="5" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> </p></div> <div class="kksr-stars-active" style="width: 0px;"> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> <div class="kksr-star" style="padding-right: 5px"> <div class="kksr-icon" style="width: 24px; height: 24px;"></div> </p></div> </p></div> </div> <div class="kksr-legend" style="font-size: 19.2px;"> <span class="kksr-muted">Rate this post</span> </div> </div> <p class="has-background" style="background-color:#d6f8f8"><strong>Summary: </strong>Use the <code>list("given string")</code> to extract each character of the given string and store them as individual items in a list.<br /><strong>Minimal Example:</strong><br /><code>print(list("abc"))</code></p> <p><strong>Problem</strong>: Given a string; How will you split the string into a list of characters? </p> <p><strong>Example: </strong>Let’s visualize the problem with the help of an example:</p> <figure class="wp-block-table is-style-stripes"> <table> <tbody> <tr> <td>input = “finxter”<br />output = [‘f’, ‘i’, ‘n’, ‘x’, ‘t’, ‘e’, ‘r’]</td> </tr> </tbody> </table> </figure> <p>Now that we have an overview of our problem let us dive into the solutions without further ado.</p> <h2><strong>Method 1: Using The <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" target="_blank">list</a> Constructor</strong></h2> <p><strong>Approach: </strong>One of the simplest ways to solve the given problem is to use the list constructor and pass the given string into it as the input. </p> <p><code>list()</code> creates a new list object that contains items obtained by iterating over the input iterable. Since a string is an iterable formed by combining a group of characters, hence, iterating over it using the <em>list</em> constructor yields a single character at each iteration which represents individual items in the newly formed list.</p> <p><strong>Code:</strong></p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">text = "finxter" print(list(text)) # ['f', 'i', 'n', 'x', 't', 'e', 'r']</pre> <p><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f48e.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" />Related Tutorial: <strong><a href="https://blog.finxter.com/python-list/" target="_blank" rel="noreferrer noopener">Python list() — A Simple Guide with Video</a></strong></p> <h2>Method 2: Using a <a href="https://blog.finxter.com/list-comprehension/" target="_blank" rel="noreferrer noopener">List Comprehension</a></h2> <p>Another way to split the given string into characters would be to use a <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" target="_blank">list comprehension</a> such that the list comprehension returns a new list containing each character of the given string as individual items.</p> <p><strong>Code:</strong></p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">text = "finxter" print([x for x in text]) # ['f', 'i', 'n', 'x', 't', 'e', 'r']</pre> <p><strong>Prerequisite: </strong>To understand what happened in the above code, it is essential to know what a list comprehension does. In simple words, a list comprehension in Python is a compact way of creating lists. The simple formula is <code>[expression + context]</code>, where the “<strong>expression</strong>” determines what to do with each list element. And the “<strong>context</strong>” determines what elements to select. The context can consist of an arbitrary number of <code>for</code> and <code>if</code> statements. To learn more about list comprehensions, head on to this detailed guide on <strong><a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" target="_blank">list comprehensions</a></strong>.</p> <p><strong>Explanation: </strong>Well! Now that you know what list comprehensions are, let’s try to understand what the above code does. In our solution, the context variable <code>x</code> is used to extract each character from the given string by iterating across each character of the string one by one with the help of a <code>for</code> loop. This context variable <code>x</code> also happens to be the expression of our list comprehension as it stores the individual characters of the given string as separate items in the newly formed list. </p> <p><strong>Multi-line Solution: </strong>Another approach to formulating the above solution is to use a for loop. The idea is pretty similar; however, we will not be using a list comprehension in this case. Instead, we will use a for loop to iterate across individual characters of the given string and store them one by one in a new list with the help of the append method. </p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">text = "finxter" res = [] for i in text: res.append(i) print(res) # ['f', 'i', 'n', 'x', 't', 'e', 'r']</pre> <h2><strong>Method 3: Using <a href="https://blog.finxter.com/python-map/" target="_blank" rel="noreferrer noopener">map</a> and <a href="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" target="_blank" rel="noreferrer noopener">lambda</a></strong></h2> <p>Yet another way of solving the given problem is to use a lambda function within the <code>map</code> function. Now, this is complex and certainly not the best fit solution to the given problem. However, it may (or may not ;P) be appropriate when you are handling really complex tasks. So, here’s how to use the two built-in Python functions to solve the given problem: </p> <pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import re text = "finxter" print(list(map(lambda c: c, text))) # ['f', 'i', 'n', 'x', 't', 'e', 'r']</pre> <p><strong>Explanation: </strong>The <code>map()</code> function is used to execute a specified function for each item of an iterable. In this case, the iterable is the given string and each character of the string represents an individual item within it. Now, all we need to do is to create a lambda function that simply returns the character passed to it as the input. That’s it! However, the map method will return a map object, so you must convert it to a list using the <code>list()</code> function. Silly! Isn’t it? Nevertheless, it works!</p> <h2><strong>Conclusion</strong></h2> <p>Hurrah! We have successfully solved the given problem using as many as three different ways. I hope you enjoyed this <a rel="noreferrer noopener" href="https://blog.finxter.com/" target="_blank">article</a> and it helps you in your Python coding journey. Please <a rel="noreferrer noopener" href="https://blog.finxter.com/subscribe" target="_blank">subscribe and stay tuned</a> for more interesting articles!</p> <p class="has-background" style="background-color:#fcf1f1"><strong>Related Reads:</strong><br /><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-split-a-string-and-keep-the-separators/" target="_blank">⦿</a> <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-split-a-string-and-keep-the-separators/" target="_blank"><strong>How To Split A String And Keep The Separators?</strong></a> <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-cut-a-string-in-python/" target="_blank"><br />⦿</a> <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-cut-a-string-in-python/" target="_blank"><strong>How To Cut A String In Python?</strong></a></p> <hr class="wp-block-separator has-alpha-channel-opacity" /> </div> https://www.sickgaming.net/blog/2022/10/21/python-split-string-into-characters/ |