How to use Split in Python

Learn how to use split in python.

Quick Example: How to use the split function in python

  • Create an array
    x = ‘blue,red,green’
  • Use the python split function and separator
    x.split(“,”) – the comma is used as a separator. This will split the string into a string array when it finds a comma.
  • Result
    [‘blue’, ‘red’, ‘green’]

Definition

The split() method splits a string into a list using a user specified separator. When a separator isn’t defined, whitespace(” “) is used.

Why use the Split() Function?

At some point, you may need to break a large string down into smaller chunks, or strings. This is the opposite of concatenation which merges or combines strings into one.

To do this, you use the python split function. What it does is split or breakup a string and add the data to a string array using a defined separator.

If no separator is defined when you call upon the function, whitespace will be used by default. In simpler terms, the separator is a defined character that will be placed between each variable.

Examples of the Python Split Function In Action

Let’s take a look at some examples.

Examples of the Python Split Function In Action

x = ‘blue,red,green’
x.split(“,”)

[‘blue’, ‘red’, ‘green’]
>>>

>>> a,b,c = x.split(“,”)

>>> a
‘blue’

>>> b 
‘red’

>>> c
‘green’

As you can see from this code, the function splits our original string which includes three colors and then stores each variable in a separate string. This leaves us with three strings of “a”, “b”, and “c”. Then, when you ask the interpreter to spit out the variables stored in these strings, you get the appropriate color.

Pretty neat, no? It’s also extremely useful when you’re working extensively with strings and variables.

Let’s look at another example.

Examples of the Python Split Function In Action 1

>>> words = “This is random text we’re going to split apart”

>>> words2 = words.split(“ “)

>>> words2

[‘This’, ‘is’, ‘random’, ‘text’, ‘we’re’, ‘going’, ‘to’, ‘split’, ‘apart’]

What we did here is split the larger string and store the variables as a list under the “words2” string.

Leave a Reply

Your email address will not be published. Required fields are marked *