{"id":111722,"date":"2020-04-18T09:23:24","date_gmt":"2020-04-18T09:23:24","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=7642"},"modified":"2020-04-18T09:23:24","modified_gmt":"2020-04-18T09:23:24","slug":"python-list-to-string-a-helpful-guide-with-interactive-shell","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2020\/04\/18\/python-list-to-string-a-helpful-guide-with-interactive-shell\/","title":{"rendered":"Python List to String: A Helpful Guide with Interactive Shell"},"content":{"rendered":"<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<div class=\"ast-oembed-container\"><iframe loading=\"lazy\" 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>\n<\/div>\n<\/figure>\n<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>\n<p><strong>Example<\/strong>: You want to convert list <code>['learn ', 'python ', 'fast']<\/code> to the string <code>'learn python fast'<\/code>. <\/p>\n<p><strong>Solution<\/strong>: to convert a list of strings to a string, do the following.<\/p>\n<ul>\n<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>\n<li>The string on which you call the join method is used as a delimiter between the list elements. <\/li>\n<li>If you don&#8217;t need a delimiter, just use the empty string <code>''<\/code>. <\/li>\n<\/ul>\n<p><strong>Code<\/strong>: Let&#8217;s have a look at the code.<\/p>\n<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']\nprint(''.join(lst))<\/pre>\n<p>The output is:<\/p>\n<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>\n<p>Try it yourself in our interactive Python shell:<\/p>\n<p> <iframe loading=\"lazy\" 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>\n<p>You can also use another delimiter string, for example, the comma:<\/p>\n<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']\nprint(','.join(lst))\n# learn,python,fast<\/pre>\n<h2>What Are Alternative Methods to Convert a List of Strings to a String?<\/h2>\n<p>Python is flexible&#8212;you can use multiple methods to achieve the same thing. So what are the different methods to convert a list to a string?<\/p>\n<ul>\n<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>\n<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>\n<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>\n<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>\n<\/ul>\n<p>Here are all four variants in some code:<\/p>\n<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\nprint(''.join(lst))\n# learnpythonfast # Method 2\ns = ''\nfor st in lst: s += st\nprint(s)\n# learnpythonfast # Method 3\nlst = ['learn', 9, 'python', 9, 'fast']\ns = ''.join([str(x) for x in lst])\nprint(s)\n# learn9python9fast # Method 4\nlst = ['learn', 9, 'python', 9, 'fast']\ns = ''.join(map(str, lst))\nprint(s)\n# learn9python9fast\n<\/pre>\n<p>Again, try to modify the delimiter string yourself using our interactive code shell:<\/p>\n<p> <iframe loading=\"lazy\" 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>\n<p>So far so good. You&#8217;ve learned how to convert a list to a string. But that&#8217;s not all! Let&#8217;s dive into some more specifics of converting a list to a string. <\/p>\n<h2>Python List to String with Commas<\/h2>\n<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&#8212;using a comma as the delimiter between the list elements?<\/p>\n<p><strong>Example<\/strong>: You want to convert list <code>['learn', 'python', 'fast']<\/code> to the string <code>'learn,python,fast'<\/code>. <\/p>\n<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>\n<p><strong>Code<\/strong>: Let&#8217;s have a look at the code.<\/p>\n<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']\nprint(','.join(lst))<\/pre>\n<p>The output is:<\/p>\n<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>\n<h2>Python List to String with Spaces<\/h2>\n<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&#8212;using a space as the delimiter between the list elements?<\/p>\n<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>\n<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>\n<p><strong>Code<\/strong>: Let&#8217;s have a look at the code.<\/p>\n<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']\nprint(' '.join(lst))<\/pre>\n<p>The output is:<\/p>\n<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>\n<h2>Python List to String with Newlines<\/h2>\n<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&#8212;using a newline character as the delimiter between the list elements?<\/p>\n<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>\n<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\npython\nfast'''<\/pre>\n<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>\n<p><strong>Code<\/strong>: Let&#8217;s have a look at the code.<\/p>\n<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']\nprint('\\n'.join(lst))<\/pre>\n<p>The output is:<\/p>\n<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\npython\nfast<\/pre>\n<h2>Python List to String with Quotes<\/h2>\n<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&#8212;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>\n<p><strong>Example<\/strong>: You want to convert list <code>['learn', 'python', 'fast']<\/code> to the string <code>'\"learn\", \"python\", \"fast\"'<\/code> :<\/p>\n<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>\n<p><strong>Code<\/strong>: Let&#8217;s have a look at the code.<\/p>\n<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']\nprint(', '.join('\"' + x + '\"' for x in lst))\n<\/pre>\n<p>The output is:<\/p>\n<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>\n<h2>Python List to String with Brackets<\/h2>\n<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&#8212;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&#8217;s a list.<\/p>\n<p><strong>Example<\/strong>: You want to convert list <code>['learn', 'python', 'fast']<\/code> to the string <code>'[learn, python, fast]'<\/code> :<\/p>\n<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>\n<p><strong>Code<\/strong>: Let&#8217;s have a look at the code.<\/p>\n<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']\nprint('[' + ', '.join(lst) + ']')\n<\/pre>\n<p>The output is:<\/p>\n<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>\n<h2>Python List to String and Back<\/h2>\n<p><strong>Problem<\/strong>: You want to convert a list into a string and back to a list.<\/p>\n<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>\n<p><strong>Solution<\/strong>: Use the following two steps to convert back and forth between a string and a list:<\/p>\n<ul>\n<li>Use the built-in <code>str()<\/code> function to convert from a list to a string.<\/li>\n<li>Use the built-in <code>eval()<\/code> function to convert from a string to a list.<\/li>\n<\/ul>\n<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)\nprint(converted)\n# ['learn', 'python', 'fast']\nprint(type(converted))\n# &lt;class 'str'> original = eval(converted)\nprint(original)\n# ['learn', 'python', 'fast']\nprint(type(original))\n# &lt;class 'list'><\/pre>\n<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>\n<h2>Convert List of Int to String<\/h2>\n<p><strong>Problem<\/strong>: You want to convert a list into a string but the list contains integer values.<\/p>\n<p><strong>Example<\/strong>: Convert the list <code>[1, 2, 3]<\/code> to a string <code>'123'<\/code>.<\/p>\n<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>\n<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]\nprint(''.join(str(x) for x in lst))\n# 123<\/pre>\n<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>\n<p>If you miss the conversion from integer to string, you get the following <code>TypeError<\/code>:<\/p>\n<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]\nprint(''.join(lst)) '''\nTraceback (most recent call last): File \"C:\\Users\\xcent\\Desktop\\code.py\", line 2, in &lt;module> print(''.join(lst))\nTypeError: sequence item 0: expected str instance, int found '''<\/pre>\n<h2>Python List to String One Line<\/h2>\n<p>To convert a list to a string in one line, use either of the three methods:<\/p>\n<ul>\n<li>Use the <code>''.join(list)<\/code> method to glue together all list elements to a single string.<\/li>\n<li>Use the list comprehension method <code>[str(x) for x in lst]<\/code> to convert all list elements to type string. <\/li>\n<li>Use <code>str(list)<\/code> to convert the list to a string representation.<\/li>\n<\/ul>\n<p>Here are three examples:<\/p>\n<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']\nprint(' '.join(lst))\n# finxter is awesome lst = [1, 2, 3]\nprint([str(x) for x in lst])\n# ['1', '2', '3'] print(str(lst))\n# [1, 2, 3]<\/pre>\n<h2>Where to Go From Here<\/h2>\n<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>\n<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>\n<p>(Besides\u2014it\u2019s free and you can unsubscribe anytime so you\u2019ve nothing to lose and everything to gain.)<\/p>\n<p>join the #1 <a href=\"https:\/\/blog.finxter.com\/subscribe\/\">Python Email Academy in the world!<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Problem: Given a list of strings. How to convert the list to a string by concatenating all strings in the list? Example: You want to convert list [&#8216;learn &#8216;, &#8216;python &#8216;, &#8216;fast&#8217;] to the string &#8216;learn python fast&#8217;. Solution: to convert a list of strings to a string, do the following. Call the &#8221;.join(list) method [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-111722","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/111722","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=111722"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/111722\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=111722"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=111722"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=111722"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}