Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python | Split String and Get Last Element

#1
Python | Split String and Get Last Element

<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload='{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;871347&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;0&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;0&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;0\/5 - (0 votes)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;0&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}'>
<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:#c9ffff"><strong>Summary: </strong> Use <code>given_string.rsplit('sep', 1)[-1]</code> to split the string and get the last element. Another approach is to use <code>given_string.rpartition('sep', 1)[-1]</code></p>
<p><strong>Minimal Solution: </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="">dob = '21/08/2023'
# Method 1
print(dob.rsplit('/', 1)[-1])
# Method 2
print(dob.rpartition('/')[-1]) # OUTPUT: 2023</pre>
<hr class="wp-block-separator has-alpha-channel-opacity" />
<h2><strong>Problem Formulation</strong></h2>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4dc.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /><strong>Problem: </strong>Given a string. How will you split the string and get the last element? </p>
<p>Let’s try to understand the given problem with the help of an example:</p>
<h3>Example 1</h3>
<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=""># Input:
text = 'Java_C++_C#_Golang_Python'
# Expected Output:
Split String: ['Java_C++_C#_Golang', 'Python']
Last Element: Python</pre>
<p>In the above example, “<code>_</code>” is the separator. However, not the entire string has been split. Only the last substring that comes after the separator has been extracted.</p>
<h3>Example 2</h3>
<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=""># Input:
text = 'Java_C++_C#_Golang_Python_'
# Expected Output:
Split String: ['Java_C++_C#_Golang', 'Python']
Last Element: Python</pre>
<p>Unlike the previous example, the input string ends with the separator itself. However, the output is similar. So, you have a different input string, but you have to generate a similar output by eliminating the separator. </p>
<hr class="wp-block-separator has-alpha-channel-opacity" />
<p>Let’s dive into the different ways of solving the given problems.</p>
<h2>Method 1: Using <a href="https://blog.finxter.com/python-string-rsplit/" target="_blank" rel="noreferrer noopener">rsplit</a></h2>
<p><strong>Prerequisite: </strong>Simply put, the <code data-enlighter-language="raw" class="EnlighterJSRAW">rsplit</code> method splits a given string based on a given separator and stores the characters/substrings into a list. For example, <code>finxterx42'.rsplit('x')</code> will return the list <code>['fin', 'ter', '42']</code> as an output. <code>rsplit</code> can take two arguments – </p>
<ul>
<li><code><strong>sep</strong></code>&nbsp;– The separator string on which it is split.</li>
<li><code><strong>maxsplit</strong></code> – The number of times the string is split.</li>
</ul>
<p>Thus, you can use the <code>maxsplit</code> argument to your advantage and solve the given question by setting <code>maxsplit = 1</code>. This means the string will be split along the specified separator only once from the right end. Once the string is split into two parts from the right end, all that you need to do is extract the second element from the list created by the <code>rsplit</code> method.</p>
<p><strong>Solution to Example 1: </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 = 'Java_C++_C#_Golang_Python'
print("Split String: ", text.rsplit('_', 1))
print("Last Element: ", text.rsplit('_', 1)[-1])</pre>
<p><strong>Output:</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="">Split String: ['Java_C++_C#_Golang', 'Python']
Last Element: Python</pre>
<p><strong>Solution to Example 2: </strong>In the second scenario, you must get rid of the separator that comes at the end of the string. Otherwise, simply using <code>rsplit</code> with the <code>maxsplit</code> argument will create a list that will create a list that will contain an empty character as the last item as shown below –</p>
<figure class="wp-block-image size-large is-style-default"><img loading="lazy" decoding="async" width="1024" height="142" src="https://blog.finxter.com/wp-content/uploads/2022/11/image-61-1024x142.png" alt="" class="wp-image-871455" srcset="https://blog.finxter.com/wp-content/uploads/2022/11/image-61-1024x142.png 1024w, https://blog.finxter.com/wp-content/uplo...300x42.png 300w, https://blog.finxter.com/wp-content/uplo...68x106.png 768w, https://blog.finxter.com/wp-content/uplo...age-61.png 1177w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
<p>To avoid this problem, you can use the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-string-strip/" target="_blank">strip()</a> function to get rid of the separator and then use <code>rsplit</code> as shown in the snippet below.</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 = 'Java_C++_C#_Golang_Python_'
text = text.strip('_')
print("Split String: ", text.rsplit('_', 1))
print("Last Element: ", text.rsplit('_', 1)[-1])</pre>
<p><strong>Output:</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="">Split String: ['Java_C++_C#_Golang', 'Python'] Last Element: Python</pre>
<h2>Method 2: Using <a rel="noreferrer noopener" href="https://blog.finxter.com/python-string-rpartition/" target="_blank">rparti</a><a rel="noreferrer noopener" href="https://blog.finxter.com/python-string-rpartition/" target="_blank">t</a><a rel="noreferrer noopener" href="https://blog.finxter.com/python-string-rpartition/" target="_blank">i</a><a rel="noreferrer noopener" href="https://blog.finxter.com/python-string-rpartition/" target="_blank">on</a></h2>
<p>You can also use the <code>rpartition</code> method to solve the given problem. The <code>rpartition</code> method searches for a separator substring and returns a tuple with three strings: (1) everything before the separator, (2) the separator itself, and (3) everything after it. For example: <code>finxterx42'.rpartition('x')</code> will return the following tuple: <code>('finxter', 'x', '42') </code></p>
<p>Thus, you can simply extract the last item from the tuple after the string has been cut by the <code>rpartition</code> method.</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=""># Solution to Example 1
text = 'Java_C++_C#_Golang_Python'
print("Split String: ", text.rpartition('_'))
print("Last Element: ", text.rpartition('_')[-1]) # Solution to Example 2
text = 'Java_C++_C#_Golang_Python_'
text = text.strip('_')
print("Split String: ", text.rpartition('_'))
print("Last Element: ", text.rpartition('_')[-1])</pre>
<p><strong>Output:</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="">Split String: ('Java_C++_C#_Golang', '_', 'Python')
Last Element: Python</pre>
<h2><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/2728.png" alt="✨" class="wp-smiley" style="height: 1em; max-height: 1em;" /><strong>Coding Challenge</strong></h2>
<p>Before we wrap up this tutorial, here’s a coding challenge for you to test your grip on the concept you just learned.</p>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><strong>Input:</strong> Consider the following IP Address –<br />ip = 110.210.130.140<br /><strong>Challenge: </strong>Extract the network bit from the given class A ip address and convert it to its binary form. <br /><strong>Expected Output: </strong><br />10001100<br /><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /><strong>Hint</strong>:<br />– 140 is the network bit!<br />– <a href="https://blog.finxter.com/how-to-convert-a-string-to-binary-in-python/" target="_blank" rel="noreferrer noopener">How to Convert a String to Binary in Python?</a></td>
</tr>
</tbody>
</table>
</figure>
<p><strong>Solution:</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="">ip = '110.210.130.140'
nw_bit = int(ip.rpartition('.')[-1])
print(bin(nw_bit)[2:])</pre>
<p><strong>Explanation: </strong>The solution is pretty straightforward. You first have to extract the network bit, i.e., 140. This happens to be the last item after the “<code>.</code>“. So, you can use <code>rpartition</code> and feed “.” as the separator and extract the last item (the network bit) from the tuple returned by the <code>rpartition</code> method. Since this will be a string, you must convert it to an integer and then typecast this integer to a binary number using the <code>bin</code> function to generate the final output. </p>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f30e.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /><strong>Related Read: <a href="https://blog.finxter.com/python-print-binary-without-0b/">Python Print Binary Without ‘0b’</a></strong></p>
<h2><strong>Conclusion</strong></h2>
<p> I hope you enjoyed the numerous scenarios and challenges used in this tutorial to help you learn the two different ways of splitting a string and getting the last item. Please <strong><a rel="noreferrer noopener" href="https://blog.finxter.com/subscribe/" target="_blank">subscribe</a></strong> and stay tuned for more interesting tutorials and solutions.</p>
<p class="has-base-background-color has-background"><strong><strong>Recommended 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><a rel="noreferrer noopener" href="https://blog.finxter.com/python-split-string-into-characters/" target="_blank"><br />⦿ <strong>Python | Split String into Characters</strong></a></strong></p>
</div>


https://www.sickgaming.net/blog/2022/11/...t-element/
Reply



Forum Jump:


Users browsing this thread:
3 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016