Lesson 3: .split()

.split() method is a quite simple yet very powerful tool for strings in Python. It will return a list of strings. Let’s see some examples.

Function 1: .split()

A simple but powerful string method in Python which is used for splitting words or substrings based on a specified character.

Used Where?

Python’s split() function can be incredibly handy and practical. It can be used in spliting strings based on a specified character or substring.  Although use cases are infinite here are some examples. You can use it to:
  • clean up raw data
  • separate words with space character: ” “
  • separate data with delimiters such as colon (:), common with financial data
  • separate sentences based on full stops (.)
  •  to split email address from its domain using “@” sign.

Syntax do(s)

1) In front of your .split() method, place the string you’d like to split or the variable that contains it.

2) Inside your .split() method’s parenthesis type the character or substring you’d like to split your string based on.

Syntax don't(s)

1) Don’t forget to type your character inside the .split() method parenthesis inside quotation marks. i.e.: str.split("@")

Example 1

>>> lyric = “Do you come from a land down under?”
>>> a = lyric.split(” “)
>>> print(a
)

[“Do”, “you”, “come”, “from”, “a”, “land”, “down”, “under?”]

Notice how we used space character inside the .split() function’s parenthesis.

Example 2

Splitting an email

>>> prof_address = “john@nyu.edu”
>>> print(prof_address.split(“@”))

[“john”, “nyu.edu”]

Example 3

Let’s use a step as well

>>> cities = “London, Paris, Mumbai, Moscow, Berlin”
>>> print(cities.split(“,”))

[“London”, “Paris”, “Mumbai”, “Moscow”, “Berlin”]

Tips

1- If you just use quotes with nothing in them with your split method, it will separate the string based on spaces. 2- You can also use the .split() method with the string directly without any variables involved.

Let’s see an example.

Example 4

>>> lyric = “Do you come from a land down under?”
>>> a = lyric.split(” “)
>>> print(a
)

[“Do”, “you”, “come”, “from”, “a”, “land”, “down”, “under?”]

Notice how we used space character inside the .split() function’s parenthesis.

Example 5

>>> print(“112.50:154.20:135.50”.split(“:”))

[“112.50”, “154.20”, “135.50”]

Advanced Concepts (Optional)

1- Split method also takes a maxsplit parameter which defines the number of splits that should take place.

If you don’t use the maxsplit parameter it is going to be -1 by default meaning no limit on the amount of splits.

Let’s see an example.

Example 6

Below example will give everything until last 2 elements

>>> suntime = “Aruba | Keys | Miami | Myrtle | Daytona”
>>> print(suntime.split(“|”, maxsplit=2)) 

[“Aruba”, “Keys”, “Miami | Myrtle | Daytona”]

Next Lesson:

strip() method

Robert Genn - Alpenglow in the Bugaboos


Robert Genn

Alpenglow in the Bugaboos

Alpenglow in the Bugaboos by Robert Genn