[Tut] Python List to String: A Helpful Guide with Interactive Shell - 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 List to String: A Helpful Guide with Interactive Shell (/thread-94622.html) |
[Tut] Python List to String: A Helpful Guide with Interactive Shell - xSicKxBot - 04-18-2020 Python List to String: A Helpful Guide with Interactive Shell <div><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="Python List to String: A Helpful Guide" width="1400" height="788" src="https://www.youtube.com/embed/2DaXCB1gusI?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div> </div> </figure> <p><strong>Problem</strong>: Given a list of strings. How to convert the list to a string by <a href="https://blog.finxter.com/concatenate-lists-in-python/" target="_blank" rel="noreferrer noopener">concatenating</a> all strings in the list?</p> <p><strong>Example</strong>: You want to convert list <code>['learn ', 'python ', 'fast']</code> to the string <code>'learn python fast'</code>. </p> <p><strong>Solution</strong>: to convert a list of strings to a string, do the following.</p> <ul> <li>Call the <code>''.join(list)</code> method on the empty string <code>''</code> that glues together all strings in the <code>list</code> and returns a new string. </li> <li>The string on which you call the join method is used as a delimiter between the list elements. </li> <li>If you don’t need a delimiter, just use the empty string <code>''</code>. </li> </ul> <p><strong>Code</strong>: Let’s have a look at the 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 = ['learn ', 'python ', 'fast'] print(''.join(lst))</pre> <p>The output is:</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="">learn python fast</pre> <p>Try it yourself in our interactive Python shell:</p> <p> <iframe height="400px" width="100%" src="https://repl.it/@finxter/joinpythonstringlist?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals"></iframe> </p> <p>You can also use another delimiter string, for example, the comma:</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 = ['learn' , 'python', 'fast'] print(','.join(lst)) # learn,python,fast</pre> <h2>What Are Alternative Methods to Convert a List of Strings to a String?</h2> <p>Python is flexible—you can use multiple methods to achieve the same thing. So what are the different methods to convert a list to a string?</p> <ul> <li><strong>Method 1</strong>: Use the method <code>''.join(list)</code> to concatenate all strings in a given list to a single list. The string on which you call the method is the delimiter between the list elements. </li> <li><strong>Method 2</strong>: Start with an empty string variable. Use a simple for loop to iterate over all elements in the list and add the current element to the string variable.</li> <li><strong>Method 3</strong>: Use <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" target="_blank">list comprehension</a> <code>[str(x) for x in list]</code> if the list contains elements of different types to convert all elements to the string data type. Combine them using the <code>''.join(newlist)</code> method. </li> <li><strong>Method 4</strong>: Use the <a rel="noreferrer noopener" href="https://blog.finxter.com/daily-python-puzzle-string-encrpytion-ord-function-map-function/" target="_blank">map function</a> <code>map(str, list]</code> if the list contains elements of different types to convert all elements to the string data type. Combine them using the <code>''.join(newlist)</code> method.</li> </ul> <p>Here are all four variants in some 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 = ['learn' , 'python', 'fast'] # Method 1 print(''.join(lst)) # learnpythonfast # Method 2 s = '' for st in lst: s += st print(s) # learnpythonfast # Method 3 lst = ['learn', 9, 'python', 9, 'fast'] s = ''.join([str(x) for x in lst]) print(s) # learn9python9fast # Method 4 lst = ['learn', 9, 'python', 9, 'fast'] s = ''.join(map(str, lst)) print(s) # learn9python9fast </pre> <p>Again, try to modify the delimiter string yourself using our interactive code shell:</p> <p> <iframe height="800px" width="100%" src="https://repl.it/@finxter/listtostring?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals"></iframe> </p> <p>So far so good. You’ve learned how to convert a list to a string. But that’s not all! Let’s dive into some more specifics of converting a list to a string. </p> <h2>Python List to String with Commas</h2> <p><strong>Problem</strong>: Given a list of strings. How to convert the list to a string by <a rel="noreferrer noopener" href="https://blog.finxter.com/concatenate-lists-in-python/" target="_blank">concatenating</a> all strings in the list—using a comma as the delimiter between the list elements?</p> <p><strong>Example</strong>: You want to convert list <code>['learn', 'python', 'fast']</code> to the string <code>'learn,python,fast'</code>. </p> <p><strong>Solution</strong>: to convert a list of strings to a string, call the <code>','.join(list)</code> method on the delimiter string <code>','</code> that glues together all strings in the <code>list</code> and returns a new string. </p> <p><strong>Code</strong>: Let’s have a look at the 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 = ['learn', 'python', 'fast'] print(','.join(lst))</pre> <p>The output is:</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="">learn,python,fast</pre> <h2>Python List to String with Spaces</h2> <p><strong>Problem</strong>: Given a list of strings. How to convert the list to a string by <a rel="noreferrer noopener" href="https://blog.finxter.com/concatenate-lists-in-python/" target="_blank">concatenating</a> all strings in the list—using a space as the delimiter between the list elements?</p> <p><strong>Example</strong>: You want to convert list <code>['learn', 'python', 'fast']</code> to the string <code>'learn python fast'</code>. (Note the empty spaces between the terms.)</p> <p><strong>Solution</strong>: to convert a list of strings to a string, call the <code>' '.join(list)</code> method on the string <code>' '</code> (space character) that glues together all strings in the <code>list</code> and returns a new string. </p> <p><strong>Code</strong>: Let’s have a look at the 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 = ['learn', 'python', 'fast'] print(' '.join(lst))</pre> <p>The output is:</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="">learn python fast</pre> <h2>Python List to String with Newlines</h2> <p><strong>Problem</strong>: Given a list of strings. How to convert the list to a string by <a rel="noreferrer noopener" href="https://blog.finxter.com/concatenate-lists-in-python/" target="_blank">concatenating</a> all strings in the list—using a newline character as the delimiter between the list elements?</p> <p><strong>Example</strong>: You want to convert list <code>['learn', 'python', 'fast']</code> to the string <code>'learn\npython\nfast'</code> or as a multiline 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="">'''learn python fast'''</pre> <p><strong>Solution</strong>: to convert a list of strings to a string, call the <code>'\n'.join(list)</code> method on the newline character <code>'\n'</code> that glues together all strings in the <code>list</code> and returns a new string. </p> <p><strong>Code</strong>: Let’s have a look at the 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 = ['learn', 'python', 'fast'] print('\n'.join(lst))</pre> <p>The output is:</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="">learn python fast</pre> <h2>Python List to String with Quotes</h2> <p><strong>Problem</strong>: Given a list of strings. How to convert the list to a string by <a rel="noreferrer noopener" href="https://blog.finxter.com/concatenate-lists-in-python/" target="_blank">concatenating</a> all strings in the list—using a comma character followed by an empty space as the delimiter between the list elements? Additionally, you want to wrap each string in double quotes.</p> <p><strong>Example</strong>: You want to convert list <code>['learn', 'python', 'fast']</code> to the string <code>'"learn", "python", "fast"'</code> :</p> <p><strong>Solution</strong>: to convert a list of strings to a string, call the <code>', '.join('"' + x + '"' for x in lst)</code> method on the delimiter string <code>', '</code> that glues together all strings in the <code>list</code> and returns a new string. You use a generator expression to modify each element of the original element so that it is enclosed by the double quote <code>"</code> chararacter. </p> <p><strong>Code</strong>: Let’s have a look at the 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 = ['learn', 'python', 'fast'] print(', '.join('"' + x + '"' for x in lst)) </pre> <p>The output is:</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="">"learn", "python", "fast"</pre> <h2>Python List to String with Brackets</h2> <p><strong>Problem</strong>: Given a list of strings. How to convert the list to a string by <a rel="noreferrer noopener" href="https://blog.finxter.com/concatenate-lists-in-python/" target="_blank">concatenating</a> all strings in the list—using a comma character followed by an empty space as the delimiter between the list elements? Additionally, you want to wrap the whole string in a square bracket to indicate that’s a list.</p> <p><strong>Example</strong>: You want to convert list <code>['learn', 'python', 'fast']</code> to the string <code>'[learn, python, fast]'</code> :</p> <p><strong>Solution</strong>: to convert a list of strings to a string, call the <code>'[' + ', '.join(lst) + ']'</code> method on the delimiter string <code>', '</code> that glues together all strings in the <code>list</code> and returns a new string.</p> <p><strong>Code</strong>: Let’s have a look at the 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 = ['learn', 'python', 'fast'] print('[' + ', '.join(lst) + ']') </pre> <p>The output is:</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="">[learn, python, fast]</pre> <h2>Python List to String and Back</h2> <p><strong>Problem</strong>: You want to convert a list into a string and back to a list.</p> <p><strong>Example</strong>: Convert the list <code>['learn', 'python', 'fast']</code> to a string <code>"['learn', 'python', 'fast']"</code> and back to a list <code>['learn', 'python', 'fast']</code>. </p> <p><strong>Solution</strong>: Use the following two steps to convert back and forth between a string and a list:</p> <ul> <li>Use the built-in <code>str()</code> function to convert from a list to a string.</li> <li>Use the built-in <code>eval()</code> function to convert from a string to a list.</li> </ul> <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 = ['learn', 'python', 'fast'] converted = str(lst) print(converted) # ['learn', 'python', 'fast'] print(type(converted)) # <class 'str'> original = eval(converted) print(original) # ['learn', 'python', 'fast'] print(type(original)) # <class 'list'></pre> <p>Although the output of both the converted list and the original list look the same, you can see that the data type is <code>string</code> for the former and <code>list</code> for the latter. </p> <h2>Convert List of Int to String</h2> <p><strong>Problem</strong>: You want to convert a list into a string but the list contains integer values.</p> <p><strong>Example</strong>: Convert the list <code>[1, 2, 3]</code> to a string <code>'123'</code>.</p> <p><strong>Solution</strong>: Use the join method in combination with a <a href="https://blog.finxter.com/list-comprehension/" target="_blank" rel="noreferrer noopener">generator expression</a> to convert the list of integers to a single string value: </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] print(''.join(str(x) for x in lst)) # 123</pre> <p>The generator expression converts each element in the list to a string. You can then combine the string elements using the join method of the string object. </p> <p>If you miss the conversion from integer to string, you get the following <code>TypeError</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, 2, 3] print(''.join(lst)) ''' Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 2, in <module> print(''.join(lst)) TypeError: sequence item 0: expected str instance, int found '''</pre> <h2>Python List to String One Line</h2> <p>To convert a list to a string in one line, use either of the three methods:</p> <ul> <li>Use the <code>''.join(list)</code> method to glue together all list elements to a single string.</li> <li>Use the list comprehension method <code>[str(x) for x in lst]</code> to convert all list elements to type string. </li> <li>Use <code>str(list)</code> to convert the list to a string representation.</li> </ul> <p>Here are three examples:</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 = ['finxter', 'is', 'awesome'] print(' '.join(lst)) # finxter is awesome lst = [1, 2, 3] print([str(x) for x in lst]) # ['1', '2', '3'] print(str(lst)) # [1, 2, 3]</pre> <h2>Where to Go From Here</h2> <p>Want to increase your Python skill on a daily basis? Just by following a series of FREE Python course emails? Then join the #1 <a href="https://blog.finxter.com/subscribe/">Python Email Academy in the world!</a></p> <p>For my subscribers, I regularly publish educative emails about the most important Python topics. Register and join my community of thousands of ambitious coders. I guarantee, you will love it!</p> <p>(Besides—it’s free and you can unsubscribe anytime so you’ve nothing to lose and everything to gain.)</p> <p>join the #1 <a href="https://blog.finxter.com/subscribe/">Python Email Academy in the world!</a></p> </div> https://www.sickgaming.net/blog/2020/04/18/python-list-to-string-a-helpful-guide-with-interactive-shell/ |