Create an account


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

#1
Python | Split String and Count Results

<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;922136&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;legendonly&quot;:&quot;&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-global-color-8-background-color has-background"><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>Summary:</strong> Split the string using split and then use len to count the results.</p>
<p><strong>Minimal Example</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="">print("Result Count: ", len('one,two,three'.split(',')))
# Result Count: 3</pre>
<hr class="wp-block-separator has-alpha-channel-opacity" />
<h2>Problem Formulation</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 find the number of split strings? Can you store the split strings into different variables?</p>
<h3><strong>Example</strong></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=""># Given String
text = '366NX-BQ62X-PQT9G-GPX4H-VT7TX'
# Expected Output:
Number of split strings: 5
key_1 = 366NX
key_2 = BQ62X
key_3 = PQT9G
key_4 = GPX4H
key_5 = VT7TX</pre>
<p>In the above problem, the delimiter used to split the string is “-“. After splitting five substrings can be extracted. Therefore, you need five variables to store the five substrings. Can you solve it?</p>
<hr class="wp-block-separator has-alpha-channel-opacity" />
<h2><strong>Solution</strong></h2>
<p>Splitting the string and counting the number of results is a cakewalk. All you have to do is split the string using the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-string-split/" target="_blank">split()</a></code> function and then use the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-len/" target="_blank">len</a></code> method upon the resultant list returned by the split method to get the number of split strings present. </p>
<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="">text = '366NX-BQ62X-PQT9G-GPX4H-VT7TX'
# splitting the string using - as separator
res = text.split('-')
# length of split string list
x = len(res)
print("Number of split strings: ", x)</pre>
<h3><strong>Approach 1</strong></h3>
<figure class="wp-block-image size-full is-style-default"><img loading="lazy" decoding="async" width="600" height="337" src="https://blog.finxter.com/wp-content/uploads/2022/11/Split-String-and-Count-Results.gif" alt="" class="wp-image-922384" /></figure>
<ul>
<li>The idea here is to find the length of the results and then use this length to create another list containing all the variable names as items within it. This can be done with a simple for loop. </li>
<li>Now, you have two <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" target="_blank">lists</a>. One that stores the split strings and another that stores the variable names that will store the split strings. </li>
<li>So, you can create a dictionary out of the two lists such that the keys in this dictionary will be the items of the list containing the variable names and the values in this dictionary will be the items of the list containing the split strings. <strong>Read: <a href="https://blog.finxter.com/how-to-convert-two-lists-into-a-dictionary/" target="_blank" rel="noreferrer noopener">How to Convert Two Lists Into A Dictionary</a></strong></li>
</ul>
<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 = '366NX-BQ62X-PQT9G-GPX4H-VT7TX'
# splitting the string using - as separator
res = text.split('-')
# length of split string list
x = len(res) # Naming and storing variables and values
name = []
for i in range(1, x+1): name.append('key_'+str(i)) d = dict(zip(name, res))
for key, value in d.items(): print(key, "=", value)</pre>
<h3><strong>Approach 2</strong></h3>
<p>Almost all modules have a special attribute known as <code>__dict__</code> which is a dictionary containing the module’s symbol table. It is essentially a dictionary or a mapping object used to store an object’s (writable) attributes. </p>
<p>So, you can create a class and then go ahead create an instance of this class which can be used to set different attributes. Once you split the given string and also create the list containing the variable names (as done in the previous solution), you can go ahead and zip the two lists and use the <code>setattr()</code> method to assign the variable and their values which will serve as the attributes of the previously created class object. Once, you have set the attributes (i.e. the variable names and their values) and attached them to the object, you can access them using the built-in <code>__dict__</code> as <code>object_name.__dict__</code></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 = '366NX-BQ62X-PQT9G-GPX4H-VT7TX'
# splitting the string using - as separator
res = text.split('-')
# length of split string list
x = len(res)
print("Number of split strings: ", x) # variable creation and value assignment
name = []
for i in range(1, x + 1): name.append('key_' + str(i)) class Record(): pass r = Record() for name, value in zip(name, res): setattr(r, name, value)
print(r.__dict__) for key, value in r.__dict__.items(): print(key, "=", value)</pre>
<h3><strong>Approach 3</strong></h3>
<p><strong>Caution: </strong>This solution is not recommended unless this is the only option left. I have mentioned this just because it solves the purpose. However, it is certainly not the best way to approach the given problem. </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 = '366NX-BQ62X-PQT9G-GPX4H-VT7TX'
# splitting the string using - as separator
res = text.split('-')
# length of split string list
x = len(res)
print("Number of split strings: ", x)
name = []
for i in range(1, x + 1): name.append('key_' + str(i)) for idx, value in enumerate(res): globals()["key_" + str(idx + 1)] = value
print(globals())
x = 0
for i in reversed(globals()): print(i, "=", globals()[i]) x = x+1 if x == 5: break</pre>
<p><strong>Explanation: </strong><code>globals()</code> function returns a dictionary containing all the variables in the global scope with the variable names as the key and the value assigned to the variable will be the value in the dictionary. You can reference this dictionary and add new variables by string name (<code>globals()['a'] = 'b'</code> sets variable <code>a</code> equal to <code>"b"</code>), however this is generally a terrible thing to do. </p>
<p>Since global returns a dictionary containing all the variables in the global scope, a workaround to get only the variables we assigned is to extract the last “N” key-value pairs from this dictionary where “N” is the length of the split string list.</p>
<h2>Conclusion</h2>
<p>I hope the solutions mentioned in this tutorial have helped you. Please stay tuned and <strong><a href="https://blog.finxter.com/subscribe/" target="_blank" rel="noreferrer noopener">subscribe</a></strong> for more interesting reads and solutions in the future. Happy coding!</p>
<hr class="wp-block-separator has-alpha-channel-opacity" />
</div>


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



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016