Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] The Most Pythonic Way to Convert a List of Tuples to a String

#1
The Most Pythonic Way to Convert a List of Tuples to a String

<div><figure class="wp-block-image size-large is-resized"><img src="https://blog.finxter.com/wp-content/uploads/2020/06/convert-1024x576.jpg" alt="Convert List of Tuples to String" class="wp-image-9242" width="768" height="432" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/convert-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w" sizes="(max-width: 768px) 100vw, 768px" /></figure>
<p class="has-background has-luminous-vivid-amber-background-color"><strong>The most Pythonic way to convert a list of tuples to a string is to use the built-in method <code>str(...)</code>. If you want to customize the delimiter string, the most Pythonic way is to concatenate the <code>join()</code> method and the <code>map()</code> function <code>'\n'.join(map(str, lst))</code> to convert all tuples to strings and gluing those together with the new-line delimiter <code>'\n'</code>. </strong></p>
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="The Most Pythonic Way to Convert a List of Tuples to a String" width="1400" height="788" src="https://www.youtube.com/embed/TRlWAz4DGQc?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p><em><strong>Exercise</strong>: Run the interactive code snippet. Which method do you like most?</em></p>
<p> <iframe src="https://trinket.io/embed/python/ad8db38a29" marginwidth="0" marginheight="0" allowfullscreen="" width="100%" height="356" frameborder="0"></iframe> </p>
<h2>Method 1: Default String Conversion</h2>
<p>Say, you’ve got a list of tuples, and you want to convert it to a string (e.g., see <a rel="noreferrer noopener" href="https://stackoverflow.com/questions/3292643/python-convert-list-of-tuples-to-string" target="_blank">this </a>SO post). The easiest way to accomplish this is to use the default string conversion method <code>str(...)</code>. </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="">>>> lst = [(1,1), (2,1), (4,2)]
>>> str(lst) '[(1, 1), (2, 1), (4, 2)]'</pre>
<p>The result is a nicely formatted string representation of your list of tuples.</p>
<h2>Method 2: Join() and Map()</h2>
<p>However, if you want to customize the <a href="https://blog.finxter.com/python-join-list/" target="_blank" rel="noreferrer noopener">delimiter </a>string, you can use the <code>join()</code> method in combination with the <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-get-rid-of-pythons-map-function-with-list-comprehension/" target="_blank"><code>map()</code> function</a>:</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="">lst = [(1,1), (2,1), (4,2)] print('--'.join(map(str, lst)))
# (1, 1)--(2, 1)--(4, 2)</pre>
<p>The <code>map()</code> function transforms each tuple into a string value, and the <code>join()</code> method transforms the <a rel="noreferrer noopener" href="https://blog.finxter.com/python-join-list/" target="_blank">collection </a>of strings to a single string—using the given delimiter <code>'--'</code>. If you forget to transform each tuple into a string with the <code>map()</code> function, you’ll get a <code>TypeError</code> because the <code>join()</code> method expects a collection of strings. </p>
<h2>Method 3: Flatten List of Tuples</h2>
<p>If you want to <a rel="noreferrer noopener" href="https://blog.finxter.com/join-list-of-lists/" target="_blank">flatten the list</a> and integrate all <a href="https://blog.finxter.com/how-to-convert-list-of-tuples-to-list-of-lists-in-python/" target="_blank" rel="noreferrer noopener">tuple </a>elements into a single large collection of elements, you can use a simple <a href="https://blog.finxter.com/list-comprehension/" target="_blank" rel="noreferrer noopener">list comprehension</a> statement <code>[str(x) for t in lst for x in t]</code>. </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="">lst = [(1,1), (2,1), (4,2)] print('\n'.join([str(x) for t in lst for x in t])) '''
1
1
2
1
4
2 '''</pre>
<p>If you want to redefine <a href="https://blog.finxter.com/the-separator-and-end-arguments-of-the-python-print-function/" target="_blank" rel="noreferrer noopener">how to print each tuple</a>—for example, separating all tuple values by a single whitespace character—use the following method based on a combination of the <code>join()</code> method and the <code>map()</code> function with a custom lambda function <code>lambda x: str(x[0]) + ' ' + str(x[1])</code> to be applied to each list element. </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="">lst = [(1,1), (2,1), (4,2)] print('\n'.join(map(lambda x: str(x[0]) + ' ' + str(x[1]), lst))) '''
1 1
2 1
4 2 '''</pre>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p></p>
</div>


https://www.sickgaming.net/blog/2020/06/...-a-string/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016