{"id":1637,"date":"2024-02-24T23:03:49","date_gmt":"2024-02-24T17:33:49","guid":{"rendered":"https:\/\/geekpython.in\/?p=1637"},"modified":"2024-02-24T23:03:50","modified_gmt":"2024-02-24T17:33:50","slug":"python-split-method","status":"publish","type":"post","link":"https:\/\/geekpython.in\/python-split-method","title":{"rendered":"Python split() method to split the string"},"content":{"rendered":"\n<p>The <code>split()<\/code> is a built-in method in Python and is <strong>used to<\/strong> <strong>split a string into substrings (words) based on a separator or delimiter<\/strong> which it takes as an argument. It returns a list containing the substrings separated by a specified delimiter(separator).<\/p>\n\n\n\n<figure data-wp-context=\"{&quot;imageId&quot;:&quot;69dbfe8a1670c&quot;}\" data-wp-interactive=\"core\/image\" class=\"wp-block-image size-full wp-lightbox-container\"><img loading=\"lazy\" decoding=\"async\" width=\"1600\" height=\"840\" data-wp-class--hide=\"state.isContentHidden\" data-wp-class--show=\"state.isContentVisible\" data-wp-init=\"callbacks.setButtonStyles\" data-wp-on-async--click=\"actions.showLightbox\" data-wp-on-async--load=\"callbacks.setButtonStyles\" data-wp-on-async-window--resize=\"callbacks.setButtonStyles\" src=\"https:\/\/geekpython.in\/wp-content\/uploads\/2024\/02\/splitvisual.png\" alt=\"Splitting a test using the split() method\" class=\"wp-image-1641\" srcset=\"https:\/\/geekpython.in\/wp-content\/uploads\/2024\/02\/splitvisual.png 1600w, https:\/\/geekpython.in\/wp-content\/uploads\/2024\/02\/splitvisual-300x158.png 300w, https:\/\/geekpython.in\/wp-content\/uploads\/2024\/02\/splitvisual-1024x538.png 1024w, https:\/\/geekpython.in\/wp-content\/uploads\/2024\/02\/splitvisual-768x403.png 768w, https:\/\/geekpython.in\/wp-content\/uploads\/2024\/02\/splitvisual-1536x806.png 1536w\" sizes=\"auto, (max-width: 1600px) 100vw, 1600px\" \/><button\n\t\t\tclass=\"lightbox-trigger\"\n\t\t\ttype=\"button\"\n\t\t\taria-haspopup=\"dialog\"\n\t\t\taria-label=\"Enlarge\"\n\t\t\tdata-wp-init=\"callbacks.initTriggerButton\"\n\t\t\tdata-wp-on-async--click=\"actions.showLightbox\"\n\t\t\tdata-wp-style--right=\"state.imageButtonRight\"\n\t\t\tdata-wp-style--top=\"state.imageButtonTop\"\n\t\t>\n\t\t\t<svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"12\" height=\"12\" fill=\"none\" viewBox=\"0 0 12 12\">\n\t\t\t\t<path fill=\"#fff\" d=\"M2 0a2 2 0 0 0-2 2v2h1.5V2a.5.5 0 0 1 .5-.5h2V0H2Zm2 10.5H2a.5.5 0 0 1-.5-.5V8H0v2a2 2 0 0 0 2 2h2v-1.5ZM8 12v-1.5h2a.5.5 0 0 0 .5-.5V8H12v2a2 2 0 0 1-2 2H8Zm2-12a2 2 0 0 1 2 2v2h-1.5V2a.5.5 0 0 0-.5-.5H8V0h2Z\" \/>\n\t\t\t<\/svg>\n\t\t<\/button><\/figure>\n\n\n\n<p>In simple terms, you have a sentence and you want to split it into words making them different entities, you can use the <code>split()<\/code> method and it will return a list containing the words.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" >sentence = \"You are good\"\n\n# Splitting sentence into array of words\nresult = sentence.split()\nprint(result)<\/pre><\/div>\n\n\n\n<p>The above code will split the string stored in the <code>sentence<\/code> variable into three words within a list.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:sh decode:true \" >['You', 'are', 'good']<\/pre><\/div>\n\n\n\n<p>You may be wondering how the string got separated when there is no delimiter specified as an argument.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Syntax<\/h2>\n\n\n\n<p><code><strong>.split(sep=None, maxsplit=-1)<\/strong><\/code><\/p>\n\n\n\n<p><code>sep<\/code> &#8211; If <code>sep<\/code> is not specified, the whitespace character is used as the delimiter otherwise, the string will be split based on the specified <code>sep<\/code>.<\/p>\n\n\n\n<p><code>maxsplit<\/code> &#8211; If <code>maxsplit<\/code> is not specified, the string will split until it reaches the end, creating as many elements as possible. Otherwise, if <code>maxsplit<\/code> is specified, the string will be split into <code>maxsplit + 1<\/code> elements. For example, if you&#8217;ve specified <code>maxsplit=1<\/code>, then the string will split into 2 elements.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Splitting based on delimiter<\/h2>\n\n\n\n<p>Suppose you have a comma-separated sentence and you want to split that sentence into a list of substrings based on the comma, you can simply pass the separator as a comma (<code>\",\"<\/code>) and be done.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python mark:4 decode:true \" >sentence = \"Sachin, Yashwant, Rishu, Abhishek, are good\"\n\n# Splitting sentence based on comma\nresult = sentence.split(sep=\",\")\nprint(result)<\/pre><\/div>\n\n\n\n<p>If you run this code, you&#8217;ll get the following output.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:sh decode:true \" >['Sachin', ' Yashwant', ' Rishu', ' Abhishek', ' are good']<\/pre><\/div>\n\n\n\n<p>You can see that the <code>split(sep=\",\")<\/code> split the sentence where the comma is placed and you get five substrings within a list.<\/p>\n\n\n\n<p>You can split the string based on any delimiter such as commas, spaces, tabs, semicolons, etc., depending on the specific requirements of the data being processed.<\/p>\n\n\n\n<p>Suppose you have the data containing names separated by a weird expression and you want to take out the names from the data.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" >sentence = \"Sachin\/&lt;&gt;\/Yashwant\/&lt;&gt;\/Rishu\/&lt;&gt;\/Abhishek\/&lt;&gt;\/Yogesh\"\n\n# Splitting\nresult = sentence.split(sep=\"\/&lt;&gt;\/\")\nprint(result)<\/pre><\/div>\n\n\n\n<p>This will work as fine as the code from the previous and you&#8217;ll get the list of names from the data and you can perform whatever operation you want.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:zsh decode:true \" >['Sachin', 'Yashwant', 'Rishu', 'Abhishek', 'Yogesh']<\/pre><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Using maxsplit<\/h2>\n\n\n\n<p>If you have a specific number in mind for how your string should be split, you can use the <code>maxsplit<\/code> to specify that number.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" >sentence = \"Sachin\/&lt;&gt;\/Yashwant\/&lt;&gt;\/Rishu\/&lt;&gt;\/Abhishek\/&lt;&gt;\/Yogesh\"\n\n# Using maxsplit\nresult = sentence.split(sep=\"\/&lt;&gt;\/\", maxsplit=3)\nprint(result)<\/pre><\/div>\n\n\n\n<p>In the above code, the <code>maxsplit<\/code> is set to <code>3<\/code> which means the string will be split into four substrings.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:sh decode:true \" >['Sachin', 'Yashwant', 'Rishu', 'Abhishek\/&lt;&gt;\/Yogesh']<\/pre><\/div>\n\n\n\n<p>The string got split into four substrings instead of three despite setting the <code>maxsplit<\/code> to 3. This happened because, by default, one is added to the number of <code>maxsplit<\/code>, which means <code>maxsplit=3<\/code> is equivalent to <code>maxsplit=3 + 1<\/code>, resulting in a maximum of 4 parts after splitting.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Example<\/h2>\n\n\n\n<p>Assume you have a file containing a person&#8217;s information (name, age, and email address), and you want to access the data from the file and perform some operations on it.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" >def get_details(filename):\n    with open(filename, \"r\") as file:\n        lines = file.readlines()\n        result = [line.split() for line in lines]\n        return result\n\ndetails = get_details(\"names\")<\/pre><\/div>\n\n\n\n<p>The function, <code>get_details<\/code>, reads a file given by the <code>filename<\/code> parameter. It then reads all the lines from the file using <code>file.readlines()<\/code>. Each line is split into a list of strings using the <code>split()<\/code> method, which splits the line based on whitespace by default. This creates a list of lists, where each inner list contains the individual words from each line.<\/p>\n\n\n\n<p>Finally, the function returns this list of lists, where each inner list represents the words from each line in the file.<\/p>\n\n\n\n<p>You can use the object (<code>details<\/code>) to access information about a specific person.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" >print(details[3])\nprint(details[1])\nprint(details[9])<\/pre><\/div>\n\n\n\n<p>This will print the information for the person on the third, first, and ninth indexes respectively.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:tex decode:true \" >['Isabella,', 'isabellanguyen@gmail.com,', '30']\n['Sophia,', 'sophiamartinez@yahoo.com,', '28']\n['Charlotte,', 'charlotte.gonzales@hotmail.com,', '34']<\/pre><\/div>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>The <code>split()<\/code> method is used to split a string into substrings within a list. You can also split your string based on a delimiter which you can pass as an argument to the <code>split()<\/code> method and you can control the splits by setting a value to the <code>maxsplit<\/code> parameter.<\/p>\n\n\n\n<p>Resource: <a href=\"https:\/\/docs.python.org\/3.3\/library\/stdtypes.html#str.split\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/docs.python.org\/3.3\/library\/stdtypes.html#str.split<\/a><\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>\ud83c\udfc6<strong>Other articles you might be interested in if you liked this one<\/strong><\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/understanding-if-__name__-__main__-in-python-programs\">Why if __name__ == \u2018__main__\u2019 is used in Python programs<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/build-websocket-server-and-client-using-python\">Create a WebSocket server and client in Python<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/map-function-in-python\">How to use map() in Python<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/understanding-pytest-to-test-python-code\">How to use pytest to test your code in Python<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/pickle-module-in-python\">Serialize and deserialize Python objects using the pickle module<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" rel=\"noreferrer noopener\" href=\"https:\/\/geekpython.in\/hash-passwords-using-bcrypt-in-python\">Hash password using the bcrypt package in Python<\/a>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><strong>That&#8217;s all for now<\/strong><\/p>\n\n\n\n<p><strong>Keep Coding\u270c\u270c<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The split() is a built-in method in Python and is used to split a string into substrings (words) based on a separator or delimiter which it takes as an argument. It returns a list containing the substrings separated by a specified delimiter(separator). In simple terms, you have a sentence and you want to split it [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":1640,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ocean_post_layout":"","ocean_both_sidebars_style":"","ocean_both_sidebars_content_width":0,"ocean_both_sidebars_sidebars_width":0,"ocean_sidebar":"","ocean_second_sidebar":"","ocean_disable_margins":"enable","ocean_add_body_class":"","ocean_shortcode_before_top_bar":"","ocean_shortcode_after_top_bar":"","ocean_shortcode_before_header":"","ocean_shortcode_after_header":"","ocean_has_shortcode":"","ocean_shortcode_after_title":"","ocean_shortcode_before_footer_widgets":"","ocean_shortcode_after_footer_widgets":"","ocean_shortcode_before_footer_bottom":"","ocean_shortcode_after_footer_bottom":"","ocean_display_top_bar":"default","ocean_display_header":"default","ocean_header_style":"","ocean_center_header_left_menu":"","ocean_custom_header_template":"","ocean_custom_logo":0,"ocean_custom_retina_logo":0,"ocean_custom_logo_max_width":0,"ocean_custom_logo_tablet_max_width":0,"ocean_custom_logo_mobile_max_width":0,"ocean_custom_logo_max_height":0,"ocean_custom_logo_tablet_max_height":0,"ocean_custom_logo_mobile_max_height":0,"ocean_header_custom_menu":"","ocean_menu_typo_font_family":"","ocean_menu_typo_font_subset":"","ocean_menu_typo_font_size":0,"ocean_menu_typo_font_size_tablet":0,"ocean_menu_typo_font_size_mobile":0,"ocean_menu_typo_font_size_unit":"px","ocean_menu_typo_font_weight":"","ocean_menu_typo_font_weight_tablet":"","ocean_menu_typo_font_weight_mobile":"","ocean_menu_typo_transform":"","ocean_menu_typo_transform_tablet":"","ocean_menu_typo_transform_mobile":"","ocean_menu_typo_line_height":0,"ocean_menu_typo_line_height_tablet":0,"ocean_menu_typo_line_height_mobile":0,"ocean_menu_typo_line_height_unit":"","ocean_menu_typo_spacing":0,"ocean_menu_typo_spacing_tablet":0,"ocean_menu_typo_spacing_mobile":0,"ocean_menu_typo_spacing_unit":"","ocean_menu_link_color":"","ocean_menu_link_color_hover":"","ocean_menu_link_color_active":"","ocean_menu_link_background":"","ocean_menu_link_hover_background":"","ocean_menu_link_active_background":"","ocean_menu_social_links_bg":"","ocean_menu_social_hover_links_bg":"","ocean_menu_social_links_color":"","ocean_menu_social_hover_links_color":"","ocean_disable_title":"default","ocean_disable_heading":"default","ocean_post_title":"","ocean_post_subheading":"","ocean_post_title_style":"","ocean_post_title_background_color":"","ocean_post_title_background":0,"ocean_post_title_bg_image_position":"","ocean_post_title_bg_image_attachment":"","ocean_post_title_bg_image_repeat":"","ocean_post_title_bg_image_size":"","ocean_post_title_height":0,"ocean_post_title_bg_overlay":0.5,"ocean_post_title_bg_overlay_color":"","ocean_disable_breadcrumbs":"default","ocean_breadcrumbs_color":"","ocean_breadcrumbs_separator_color":"","ocean_breadcrumbs_links_color":"","ocean_breadcrumbs_links_hover_color":"","ocean_display_footer_widgets":"default","ocean_display_footer_bottom":"default","ocean_custom_footer_template":"","ocean_post_oembed":"","ocean_post_self_hosted_media":"","ocean_post_video_embed":"","ocean_link_format":"","ocean_link_format_target":"self","ocean_quote_format":"","ocean_quote_format_link":"post","ocean_gallery_link_images":"on","ocean_gallery_id":[],"footnotes":""},"categories":[2,71],"tags":[31],"class_list":["post-1637","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","category-misc","tag-python3","entry","has-media"],"_links":{"self":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1637","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/comments?post=1637"}],"version-history":[{"count":3,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1637\/revisions"}],"predecessor-version":[{"id":1642,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/1637\/revisions\/1642"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media\/1640"}],"wp:attachment":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media?parent=1637"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/categories?post=1637"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/tags?post=1637"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}