{"id":129199,"date":"2022-10-25T17:11:24","date_gmt":"2022-10-25T17:11:24","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=823766"},"modified":"2022-10-25T17:11:24","modified_gmt":"2022-10-25T17:11:24","slug":"python-split-string-by-whitespace","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2022\/10\/25\/python-split-string-by-whitespace\/","title":{"rendered":"Python | Split String by Whitespace"},"content":{"rendered":"\n<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;823766&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;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;}\">\n<div class=\"kksr-stars\">\n<div class=\"kksr-stars-inactive\">\n<div class=\"kksr-star\" data-star=\"1\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"2\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"3\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"4\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"5\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<div class=\"kksr-stars-active\" style=\"width: 0px;\">\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<\/div>\n<div class=\"kksr-legend\" style=\"font-size: 19.2px;\"> <span class=\"kksr-muted\">Rate this post<\/span> <\/div>\n<\/div>\n<p class=\"has-background\" style=\"background-color:#d2fbfd\"><strong>Summary:&nbsp;<\/strong>Use&nbsp;<code>\"given string\".split()<\/code>&nbsp;to split the given string by whitespace and store each word as an individual item in a list.<br \/><strong>Minimal Example:<\/strong><br \/><code>print(\"Welcome Finxter\".split())<\/code><br \/># OUTPUT: [&#8216;Welcome&#8217;, &#8216;Finxter&#8217;]<\/p>\n<h2><strong>Problem Formulation<\/strong><\/h2>\n<p><strong>Problem<\/strong>: Given a string, How will you split the string into a list of words using whitespace as a separator\/delimiter?<\/p>\n<p>Let&#8217;s understand the problem with the help of a few examples:<\/p>\n<figure class=\"wp-block-table is-style-stripes\">\n<table>\n<tbody>\n<tr>\n<td><strong>Example 1:<\/strong><br \/><strong>Input:<\/strong> text = &#8220;Welcome to the world of Python&#8221;<br \/><strong>Explanation: <\/strong>Split the string into a list of words using a space &#8221; &#8221; as the delimiter to separate the words from the given string. <br \/><strong>Output: <\/strong><br \/>[&#8216;Welcome&#8217;, &#8216;to&#8217;, &#8216;the&#8217;, &#8216;world&#8217;, &#8216;of&#8217;, &#8216;Python&#8217;]<\/p>\n<p><strong>Example 2: <\/strong><br \/><strong>Input:<\/strong><br \/>text = &#8220;&#8221;&#8221;Item_1<br \/>Item_2<br \/>Item_3&#8243;&#8221;&#8221;<br \/>print(text.split(&#8216;\\n&#8217;))<br \/><strong>Explanation: <\/strong>Split the string into a list of words using a newline &#8220;\\n&#8221; as the delimiter to separate the words from the given string. <br \/><strong>Output:<\/strong> [&#8216;Item_1&#8217;, &#8216;Item_2&#8217;, &#8216;Item_3&#8217;]<\/p>\n<p><strong>Example 3: <\/strong><br \/>text = &#8220;This is just a random text:\\n New Line&#8221;<br \/><strong>Explanation: <\/strong>The given string contains a combination of whitespaces between the words, such as space, multiple-spaces, a tab and a new line character. All of these whitespace characters have to be considered as delimiters while separating the words from the given string and storing them as items in a list. Here&#8217;s how the output looks: <br \/><strong>Output:<\/strong><br \/>[&#8216;This&#8217;, &#8216;is&#8217;, &#8216;just&#8217;, &#8216;a&#8217;, &#8216;random&#8217;, &#8216;text:&#8217;, &#8216;New&#8217;, &#8216;Line&#8217;]<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n<p>So, we have two situations at hand. One, that has a single whitespace used as a delimiter and another that has multiple whitespace characters as delimiters in the same string. Let&#8217;s dive into the numerous ways of solving this problem. <\/p>\n<h2><strong>Method 1: Using split()<\/strong> <\/h2>\n<p><code>split()<\/code> is a built-in method in Python which splits the string at a given separator and returns a split list of substrings. Here&#8217;s a minimal example that demonstrates how the <code>split<\/code> function works &#8211; <code>finxterx42'.split('x')<\/code> will split the string with the character &#8216;x&#8217; as the delimiter and return the following list as an output: <code>['fin', 'ter', '42']<\/code>. The default separator, i.e., when no value is passed to the split function is considered as any whitespace character, i.e., it will take into account any whitespace such as &#8216;\\n&#8217;, &#8221; &#8220;, &#8216;\\t&#8217;, etc.<\/p>\n<p class=\"has-base-background-color has-background\">Read more about the <code>split()<\/code> method in this blog tutorial: <strong><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-string-split\/\" target=\"_blank\">Python String split()<\/a><\/strong>.<\/p>\n<p><strong>Approach: <\/strong>Thus to split a string based on a given whitespace delimiter, you can simply pass the specific whitespace character as a separator\/delimiter to the <code>split('whitespace_character')<\/code> function.<\/p>\n<p><strong>Code: <\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"3,10,15\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># Example 1:\ntext = \"Welcome to the world of Python\"\nprint(text.split(' '))\n# OUTPUT: ['Welcome', 'to', 'the', 'world', 'of', 'Python'] # Example 2:\ntext = \"\"\"Item 1\nItem 2\nItem 3\"\"\"\nprint(text.split('\\n'))\n# OUTPUT: ['Item_1', 'Item_2', 'Item_3'] # Example 3: text = \"This is just a\\trandom text:\\nNew Line\"\nprint(text.split()) # OUTPUT: ['This', 'is', 'just', 'a', 'random', 'text:', 'New', 'Line']<\/pre>\n<p>Note that to separate the words in the third example we did specify any separator within the <code>split()<\/code> function. This is because when you don&#8217;t specify the separator, then Python will automatically consider that any whitespace character that occurs within the given string is a separator. <\/p>\n<h2><strong>Method 2: Using <a href=\"https:\/\/blog.finxter.com\/python-regex\/\" target=\"_blank\" rel=\"noreferrer noopener\">regex<\/a><\/strong><\/h2>\n<p>Another extremely handy way of separating a string with whitespace characters as separators is to use the regex library. <\/p>\n<p><strong>Approach 1: <\/strong>Import the regex library and use its split method as <code>re.split('\\s+', text)<\/code> where &#8216;\\s+&#8217; returns a match whenever the string contains one or more whitespace characters. Therefore, whenever any whitespace character is encountered, the string will be separated at that point. <\/p>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"4, 11, 16\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import re\n# Example 1:\ntext = \"Welcome to the world of Python\"\nprint(re.split('\\s+', text))\n# OUTPUT: ['Welcome', 'to', 'the', 'world', 'of', 'Python'] # Example 2:\ntext = \"\"\"Item_1\nItem_2\nItem_3\"\"\"\nprint(re.split('\\s+', text))\n# OUTPUT: ['Item_1', 'Item_2', 'Item_3'] # Example 3:\ntext = \"This is just a\\trandom text:\\nNew Line\"\nprint(re.split('\\s+', text))\n# OUTPUT: ['This', 'is', 'just', 'a', 'random', 'text:', 'New', 'Line']<\/pre>\n<p class=\"has-base-background-color has-background\"><strong>Related Tutorial: <a href=\"https:\/\/blog.finxter.com\/python-regex-split\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python Regex Split<\/a><\/strong><\/p>\n<p><strong>Approach 2: <\/strong>Another way of using the regex library to solve this question is to use the <code>findall()<\/code> method of the regex library. Import the regex library and use <code>re.findall(r'\\S+', text)<\/code> where the expression returns all the characters\/words in a list that do not contain any whitespace character. This essentially means that whenever Python finds and segregates a string that has no whitespace in it. As soon as a whitespace character is found it considers that as a breakpoint, therefore the next word that has a continuous sequence of characters without the presence of any whitespace character is taken into account. <\/p>\n<p>Here&#8217;s a graphical representation of the above explanaton:<\/p>\n<figure class=\"wp-block-image size-full is-style-default\"><img loading=\"lazy\" decoding=\"async\" width=\"715\" height=\"456\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/10\/image-232.png\" alt=\"\" class=\"wp-image-831613\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/10\/image-232.png 715w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/10\/image-232-300x191.png 300w\" sizes=\"auto, (max-width: 715px) 100vw, 715px\" \/><\/figure>\n<p><strong>Code:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"4,11,16\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import re\n# Example 1:\ntext = \"Welcome to the world of Python\"\nprint(re.findall(r'\\S+', text))\n# OUTPUT: ['Welcome', 'to', 'the', 'world', 'of', 'Python'] # Example 2:\ntext = \"\"\"Item_1\nItem_2\nItem_3\"\"\"\nprint(re.findall(r'\\S+', text))\n# OUTPUT: ['Item_1', 'Item_2', 'Item_3'] # Example 3:\ntext = \"This is just a random text:\\n New Line\"\nprint(re.findall(r'\\S+', text))\n# OUTPUT: ['This', 'is', 'just', 'a', 'random', 'text:', 'New', 'Line']<\/pre>\n<p class=\"has-base-background-color has-background\"><strong>Related Tutorial: <a href=\"https:\/\/blog.finxter.com\/python-re-findall\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python re.findall() \u2013 Everything You Need to Know<\/a><\/strong><\/p>\n<p><strong><em>Do you want to master the regex superpower?<\/em><\/strong> Check out my new book <em><strong><a href=\"https:\/\/blog.finxter.com\/ebook-the-smartest-way-to-learn-python-regex\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"[eBook] The Smartest Way to Learn Python Regex\">The Smartest Way to Learn Regular Expressions in Python<\/a><\/strong><\/em> with the innovative 3-step approach for active learning: (1) study a book chapter, (2) solve a code puzzle, and (3) watch an educational chapter video. <\/p>\n<h2><strong>Conclusion<\/strong><\/h2>\n<p>We have successfully solved the given problem using different approaches. I hope you enjoyed this&nbsp;<a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/\" target=\"_blank\">article<\/a>&nbsp;and it helps you in your Python coding journey. Please&nbsp;<a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/subscribe\" target=\"_blank\">subscribe and stay tuned<\/a>&nbsp;for more interesting articles!<\/p>\n<p class=\"has-base-2-background-color has-background\"><strong>Related Reads:<\/strong><br \/><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/how-to-split-a-string-and-keep-the-separators\/\" target=\"_blank\">\u29bf<\/a>&nbsp;<a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/how-to-split-a-string-and-keep-the-separators\/\" target=\"_blank\"><strong>How To Split A String And Keep The Separators?<\/strong><\/a><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/how-to-cut-a-string-in-python\/\" target=\"_blank\"><br \/>\u29bf<\/a>&nbsp;<a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/how-to-cut-a-string-in-python\/\" target=\"_blank\"><strong>How To Cut A String In Python?<\/strong><\/a> <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-split-string-into-characters\/\" target=\"_blank\"><br \/>\u29bf&nbsp;<strong>Python | Split String into Characters<\/strong><\/a><\/p>\n<hr class=\"wp-block-separator has-alpha-channel-opacity\" \/>\n<div class=\"wp-container-1 wp-block-group\">\n<div class=\"wp-block-group__inner-container\">\n<h2><a href=\"https:\/\/academy.finxter.com\/university\/mastering-regular-expressions\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/academy.finxter.com\/university\/mastering-regular-expressions\/\">Python Regex Course<\/a><\/h2>\n<p><strong><em>Google engineers are regular expression masters. <\/em><\/strong>The Google search engine is a massive <em>text-processing engine<\/em> that extracts value from trillions of webpages.\u00a0\u00a0<\/p>\n<p><strong><em>Facebook engineers are regular expression masters.<\/em><\/strong> Social networks like Facebook, WhatsApp, and Instagram connect humans via <em>text messages<\/em>.\u00a0<\/p>\n<p><strong><em>Amazon engineers are regular expression masters. <\/em><\/strong>Ecommerce giants ship products based on <em>textual product descriptions<\/em>.\u00a0\u00a0Regular expressions \u200brule the game \u200bwhen text processing \u200bmeets computer science.\u00a0<\/p>\n<p><em><strong>If you want to become a regular expression master too, check out the<a href=\"https:\/\/academy.finxter.com\/university\/mastering-regular-expressions\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"https:\/\/academy.finxter.com\/university\/mastering-regular-expressions\/\"> most comprehensive Python regex course<\/a> on the planet:<\/strong><\/em><\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><a href=\"https:\/\/academy.finxter.com\/university\/mastering-regular-expressions\/\" target=\"_blank\" rel=\"noopener\"><img decoding=\"async\" loading=\"lazy\" width=\"1024\" height=\"576\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2018\/10\/ClickToPlay-1024x576.jpg\" alt=\"\" class=\"wp-image-19840\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2018\/10\/ClickToPlay-scaled.jpg 1024w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2018\/10\/ClickToPlay-300x169.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2018\/10\/ClickToPlay-768x432.jpg 768w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2018\/10\/ClickToPlay-1536x864.jpg 1536w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2018\/10\/ClickToPlay-2048x1152.jpg 2048w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2018\/10\/ClickToPlay-150x84.jpg 150w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/a><\/figure>\n<\/div>\n<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Rate this post Summary:&nbsp;Use&nbsp;&#8220;given string&#8221;.split()&nbsp;to split the given string by whitespace and store each word as an individual item in a list.Minimal Example:print(&#8220;Welcome Finxter&#8221;.split())# OUTPUT: [&#8216;Welcome&#8217;, &#8216;Finxter&#8217;] Problem Formulation Problem: Given a string, How will you split the string into a list of words using whitespace as a separator\/delimiter? Let&#8217;s understand the problem with the [&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-129199","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\/129199","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=129199"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/129199\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=129199"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=129199"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=129199"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}