Sick Gaming
[Tut] Python | Split String at Position - 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 at Position (/thread-100155.html)



[Tut] Python | Split String at Position - xSicKxBot - 10-29-2022

Python | Split String at Position

<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;838222&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:#d1faf5"><strong>Summary: </strong>You can split a given string at a specific position/index using Python’s <a rel="noreferrer noopener" href="https://blog.finxter.com/daily-python-puzzle-string-slicing/" target="_blank">string</a><a href="https://blog.finxter.com/daily-python-puzzle-string-slicing/" target="_blank" rel="noreferrer noopener">–</a><a rel="noreferrer noopener" href="https://blog.finxter.com/daily-python-puzzle-string-slicing/" target="_blank">slicing</a> syntax. </p>
<p><strong>Minimal Example:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="droide" data-enlighter-highlight="3,4,9-11" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Method 1:
s = "split string at position"
print(s[:12])
print(s[13:]) # Method 2:
import re
s = "split string at position"
pos = re.search('at', s)
l = s[:pos.start()]
r = s[pos.start():]
print(l)
print® # OUTPUT:
split string
at position</pre>
<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/1f4ac.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /><strong>Problem:</strong>&nbsp;Given a string, how will you split the given string at any given position?</p>
<p>Let’s have a look at a couple of examples that demonstrate what the problem asks you to do:</p>
<h3>◈<strong>Example 1</strong></h3>
<p>The following problem requires us to split the string into two parts. You have to cut the given string into two halves based on a certain index/position. The given cut position/index is 12. </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=""># Input
s = "split string at position"
# Output
split string
at position</pre>
<h3>◈<strong>Example 2</strong></h3>
<p>The following problem asks us to split the string based on the position of a certain character (“<code>,</code>”) and a word (“<code>or</code>”) present in the string. Thus, in this case, you have not been given the exact position or index to split the string. Instead, you have to find the index/position of certain characters and then split the string accordingly based on the positions of the given characters and words and store the required sub-strings in different variables. </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=""># Input
text = "Bob is the Relationship Manager, contact him at [email protected] or call him at 6546 "
# Output:
Personnel: Bob is the Relationship Manager
Email: contact him at [email protected]
Contact Info: call him at 6546</pre>
<hr class="wp-block-separator has-alpha-channel-opacity" />
<p>Now, let’s dive into the different ways of solving this problem. </p>
<h2><strong>Method 1: Using String Slicing</strong></h2>
<p>String slicing is the concept of carving a substring from a given string. Use slicing notation s[start Confusedtop: step] to access every step-th element starting from index start (included) and ending in index stop (excluded). All three arguments are optional, so you can skip them to use the default values (start = 0, stop = len(string), step = 1.) </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 Tutorial:</strong> <strong><a rel="noreferrer noopener" href="https://blog.finxter.com/daily-python-puzzle-string-slicing/" target="_blank">String Slicing in Python.</a></strong></p>
<h3 class="has-large-font-size">◈<strong>Example 1 Solution</strong></h3>
<p class="has-contrast-color has-text-color"><strong>Approach:</strong>&nbsp;Use string slicing to cut the given string at the required position. To do this, you have to use the square-bracket syntax within which you can specify the starting and ending indices to carve out the required sub-strings as shown in the solution below.</p>
<p><strong>Code:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="2-3" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">s = "split string at position"
print(s[:12])
print(s[13:])</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
at position</pre>
<h3 class="has-large-font-size">◈<strong>Example 2 Solution</strong></h3>
<p><strong>Approach</strong>: Use the <code>index()</code> method of the given character, i.e., “<code>,</code>” and the substring “<code>or</code>” within the given string. Then use this index to extract the required chunks of substrings by splitting the given string with the help of string slicing. </p>
<p><strong>Code:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="2, 5" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">text = "Bob is the Relationship Manager, contact him at [email protected] or call him at 6546 "
# get the position of characters where you want to split the string
pos_comma = text.index(',')
pos_or = text.index('or')
# Slice the string based on the position of comma
personnel, email, phone = text[:pos_comma], text[pos_comma+1:pos_or], text[pos_or+2:]
print(f'Personnel: {personnel}\nEmail: {email}\nContact Info: {phone}')</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="">Personnel: Bob is the Relationship Manager
Email: contact him at [email protected] Contact Info: call him at 6546 </pre>
<p><strong>Note:</strong> The <code>index()</code> method allows you to find the index of the first occurrence of a substring within a given string. You can learn more about Python’s <code>index()</code> method here: <strong><a href="https://blog.finxter.com/python-string-index/">Python String index()</a></strong>. </p>
<h2>◈<strong>Method 2: Using <a href="https://blog.finxter.com/python-regex/" target="_blank" rel="noreferrer noopener">regex</a></strong></h2>
<p>If a regular expression matches a part of your string, a lot of helpful information comes with it, for example, you can find out what’s the exact position of the match. The <code>re.search(pattern, string)</code> method is used to match the first occurrence of a specified pattern in the string and returns a match object. Thus, you can use it to solve the given problem. </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</strong>: <a href="https://blog.finxter.com/python-regex-search/"><strong>Python Regex Search</strong></a></p>
<p><strong>Pre-requisite:</strong> <code>match_object.start()</code> is a method used to get the position of the first character of the match object and <code>match_object.end()</code> is the method to get the last character of the match object.</p>
<p><em> A Quick Look at The Official Documentation:</em></p>
<figure class="wp-block-image size-full is-style-default"><img loading="lazy" width="873" height="425" src="https://blog.finxter.com/wp-content/uploads/2022/10/image-251.png" alt="" class="wp-image-842253" srcset="https://blog.finxter.com/wp-content/uploads/2022/10/image-251.png 873w, https://blog.finxter.com/wp-content/uploads/2022/10/image-251-300x146.png 300w, https://blog.finxter.com/wp-content/uploads/2022/10/image-251-768x374.png 768w" sizes="(max-width: 873px) 100vw, 873px" /><figcaption>source: <a href="https://docs.python.org/3/library/re.html#re.Match.start">https://docs.python.org/3/library/re.html#re.Match.start</a></figcaption></figure>
<h3 class="has-large-font-size">◈<strong>Example 1 Solution</strong></h3>
<p><strong>Approach: </strong></p>
<ul>
<li>Import the <code>regex</code> module and then create a match object by using the <code>re.search()</code> method.&nbsp;You can do this by passing the substring/character that lies at the given split index/position. In this case, the substring that lies at the split index is “<code>at</code>“. </li>
<li>We can then split the string by accessing the start position of the matched string object by calling the method <code>pos.start()</code> where <code>pos</code> denotes the matched object.&nbsp;</li>
<li>Then to get the first half of the split string, you can use string slicing as <code>s[:pos.start()]</code>. Here, we sliced the original string from the start index of the given string until the index of the searched character (not included) that was extracted in the previous step. </li>
<li>Further, we need the second section of the split string. Thus, we will now slice the original string from the index of the searched character to the end of the string, like so: <code>s[pos.start():]</code></li>
</ul>
<p><strong>Code:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="3-5" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import re s = "split string at position"
pos = re.search('at', s)
l = s[:pos.start()]
r = s[pos.start():]
print(l)
print®</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
at position</pre>
<h3 class="has-large-font-size">◈<strong>Example 2</strong> <strong>Solution</strong></h3>
<p>The idea is pretty similar to the solution of example 1. You just need to adjust the start and stop indices within the slice syntax with the help of the <code>start()</code> and <code>end()</code> methods to extract the required split sub-strings one by one. </p>
<p><strong>Code:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="3,6,8,10" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import re
text = "Bob is the Relationship Manager, contact him at [email protected] or call him at 6546"
# Look for the match objects
_comma = re.search(',', text)
_or = re.search('or', text)
# slice to get first substring
personnel = text[:_comma.start()]
# slice to get second substring
email = text[_comma.end()+1:_or.start()]
# slice to get third substring
phone = text[_or.end():]
# Final Output
print(f'Personnel: {personnel}\nEmail: {email}\nContact Info: {phone}')</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="">Personnel: Bob is the Relationship Manager
Email: contact him at [email protected] or
Contact Info: call him at 6546</pre>
<h2><strong>Conclusion</strong></h2>
<p>Woohoo! We have successfully solved splitting a string at the position using two different ways. I hope you enjoyed this article and it helps you in your coding journey. Please <strong><a href="https://blog.finxter.com/subscribe/">subscribe</a></strong> and <strong><a rel="noreferrer noopener" href="https://blog.finxter.com/author/shubham/" target="_blank">stay tuned</a></strong> for more such interesting articles!</p>
<p class="has-base-background-color has-background"><strong>Related Reads:</strong><br /><strong><a href="https://blog.finxter.com/python-split-string-by-whitespace/" target="_blank" rel="noreferrer noopener">⦿&nbsp;Python | Split String by Whitespace</a></strong><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-cut-a-string-in-python/" target="_blank"><br />⦿</a>&nbsp;<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 />⦿&nbsp;<strong>Python | Split String into Characters</strong></a></p>
<hr class="wp-block-separator has-alpha-channel-opacity is-style-wide" />
<p>Google, Facebook, and Amazon engineers are regular expression masters. If you want to become one as well, check out our new book: <a href="https://amzn.to/2Bcw5kK" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2Bcw5kK"><strong>The Smartest Way to Learn Python Regex</strong></a> <em>(Amazon Kindle/Print, opens in new tab)</em>.</p>
</div>


https://www.sickgaming.net/blog/2022/10/28/python-split-string-at-position/