.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. .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. A simple but powerful string method in Python which is used for splitting words or substrings based on a specified character.
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: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.
1) Don’t forget to type your character inside the .split()
method parenthesis inside quotation marks. i.e.: str.split("@")
>>> 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.
Splitting an email
>>> prof_address = “john@nyu.edu”
>>> print(prof_address.split(“@”))
[“john”, “nyu.edu”]
Let’s use a step as well
>>> cities = “London, Paris, Mumbai, Moscow, Berlin”
>>> print(cities.split(“,”))
[“London”, “Paris”, “Mumbai”, “Moscow”, “Berlin”]
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.
>>> 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.
>>> print(“112.50:154.20:135.50”.split(“:”))
[“112.50”, “154.20”, “135.50”]
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.
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