Create an account


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

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

<div><p class="has-black-color has-luminous-vivid-amber-background-color has-text-color has-background"><strong>To convert a list <code>lst</code> of strings to a string, use the <code>''.join(lst)</code> method with an empty separator string between the elements. If you have a list of objects, first convert each element to a string and join the result with the generator expression <code>''.join(str(x) for x in lst)</code>. </strong></p>
<figure class="wp-block-image size-large is-resized"><img src="https://blog.finxter.com/wp-content/uploads/2020/06/list2string-1024x576.jpg" alt="" class="wp-image-9945" width="768" height="432" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/list2string-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><strong>Problem</strong>: Given a list of elements. How to convert them to a string?</p>
<p><strong>Example</strong>: Given the following list of strings.</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 = ['a', 'b', 'c']</pre>
<p>You want to convert the list of strings to the following string:</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="">'abc'</pre>
<p>What’s the most Pythonic way of converting a list to a string? The answer depends on the nuances.</p>
<p>Here’s a quick overview before we dive into each of the methods:</p>
<p> <iframe src="https://trinket.io/embed/python/66febeb22d" width="100%" height="450" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe> </p>
<p><em><strong>Exercise</strong>: Run the code! What’s the most Pythonic way in your opinion?</em></p>
<h2>Method 1: Join List of Strings</h2>
<p>The most straightforward way is to use the <code>string.join(iterable)</code> method that concatenates all values in the <code>iterable</code> (such as a list) using the separator <code>string</code> in between the elements.</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 = ['a', 'b', 'c']
s = ''.join(lst)</pre>
<p>The output is the following string:</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(s)
# abc</pre>
<p>Due to its conciseness and efficiency, this is the most Pythonic way of converting a list of <em>strings </em>to a string. However, the join() method expects that you pass a list of strings. If you have a list of non-strings, it will throw an error! </p>
<p><strong>Related article</strong>: <a href="https://blog.finxter.com/python-join-list/" target="_blank" rel="noreferrer noopener" title="Python Join List [Ultimate Guide]">The Ultimate Guide to Python Join</a></p>
<h2>Method 2: Join List of Non-Strings with Generator Expression</h2>
<p>So, what to do if you want to convert a list of general objects to a string?</p>
<p>The most Pythonic way to <a href="https://blog.finxter.com/concatenate-lists-in-python/" target="_blank" rel="noreferrer noopener" title="How to Concatenate Lists in Python? [Interactive Guide]">concatenate </a>a list of objects is the expression <code>''.join(str(x) for x in lst)</code> that converts each object to a string using the built-in <code>str(...)</code> function in a <a href="https://blog.finxter.com/how-to-use-generator-expressions-in-python-dictionaries/" target="_blank" rel="noreferrer noopener" title="How to Use Generator Expressions in Python Dictionaries">generator expression</a>. You can concatenate the resulting list of strings using the <code>join()</code> method on the empty string as a delimiter. The result is a single string value that’s the concatenation of the objects’ string representations.</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, 2, 3]
s = ''.join(str(x) for x in lst)
print(s)
# 123</pre>
<p>This general method works for all objects (because all objects implement the <code>__str__</code> method per default). It’s the most Pythonic way of converting a list of non-string</p>
<p><strong>Related article</strong>: <a href="https://blog.finxter.com/how-to-use-pythons-join-function-on-a-list-of-objects-rather-than-strings/" target="_blank" rel="noreferrer noopener" title="How to Use Python’s Join() on a List of Objects (Not Strings)?">What’s the most Pythonic way to join a list of objects?</a></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="What's The Most Pythonic Way to Concatenate a List of Objects into a String?" width="1400" height="788" src="https://www.youtube.com/embed/_JDhMYSIDWI?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<h2>Method 3: String Concatenation with +</h2>
<p>Just for the sake of completeness, I want to highlight that you can also concatenate all strings in a list by using the + operator. If you have a list with a few objects, this is a viable option:</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 = ['a', 'b', 'c']
s = lst[0] + lst[1] + lst[2]
print(s)
# abc</pre>
<p>This is inefficient because each <code>+</code> operator creates a new string. For <code>n</code> list elements, you create <code>n-1</code> new strings in memory.</p>
<p><strong>Related article</strong>: <a href="https://blog.finxter.com/daily-python-puzzle-string-concatenation/" title="Daily Python Puzzle: String Concatenation" target="_blank" rel="noreferrer noopener">The <code>+</code> operator for string concatenation.</a></p>
<p>This must be slightly modified when concatenating a list of objects to a single string:</p>
<h2>Method 4: String Concatenation with + and str()</h2>
<p>Again, if you have a list of objects, you need to convert each object to a string first:</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=""># Method 4: String Concatenation with + and str()
lst = [1.0, 2.0, 3.0]
s = str(lst[0]) + str(lst[1]) + str(lst[2])
print(s)
# 1.02.03.0</pre>
<p>This is very tedious and it deserves to be titled the <em>“least Pythonic way to convert a list to a string”</em>. You should prefer the general <strong>Method 2</strong> that’s not only shorter and more efficient, but also more readable and generally applicable.</p>
<h2>Method 5: Use Map + Join</h2>
<p>The map function allows you to convert each element to a string first. You can then join the strings using the standard string.join() method on the resulting iterable of strings.</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, 2, 'hello', 3.2]
s = ''.join(map(str, lst))
print(s)
# 12hello3.2</pre>
<p>This works beautifully for list of objects as well and it’s quite Pythonic. Many Python coders like this functional style—but I don’t consider it the most Pythonic one. Python code should be readable. <a href="https://blog.finxter.com/about-guidos-fate-of-reduce-in-python-3000/" title="About Guido’s Article: “Fate of Reduce() in Python 3000”" target="_blank" rel="noreferrer noopener">Guido van Rossum</a>, Python’s creator, tried to avoid functional programming because he didn’t find it readable compared to <a href="https://blog.finxter.com/list-comprehension/" title="List Comprehension in Python — A Helpful Illustrated Guide" target="_blank" rel="noreferrer noopener">list comprehension</a> or its generalization “generator expressions” (see <strong>Method 2</strong>). </p>
<p><strong>Related Article</strong>: <a href="https://blog.finxter.com/daily-python-puzzle-string-encrpytion-ord-function-map-function/" title="Mastering the Python Map Function [+Video]" target="_blank" rel="noreferrer noopener">The map() function in Python</a></p>
<h2>Method 6: Simple Loop</h2>
<p>Let’s see what coders who come from another programming language such as Java would do:</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, 2, 'hello', 3.2]
s = ''
for x in lst: s += str(x)
print(s)
# 12hello3.2</pre>
<p>They’d first create an empty string. Then, they’d add the string representation of each list element to the string until all list elements are added. </p>
<p>This is highly inefficient because of the repeated creation of new strings and it needs three lines instead of one. As it’s often the case in Python, you can avoid loops by using Python’s powerful built-in capabilities.</p>
<p><strong>Related article</strong>:<a href="https://blog.finxter.com/python-vs-go-which-language-you-should-choose/" target="_blank" rel="noreferrer noopener" title="Python vs Go – Which Language You Should Choose"> Go vs Python</a></p>
<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>
</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