How to split string in Python#

So you are looking to break up a string into smaller strings (into an array if you are coming from a PHP / JavaScript background) based on a delimiter or character. Python provides a very straightforward and easy function to do that.

The function is called split, and it returns a list as the result (you really don't want to a Python array for this one).

Here are some examples. The examples are to be tried at the Python console.

Example 1: print a list of web technologies

>>> s = 'python,jquery,javascript'
>>> s.split(",")
['python', 'jquery', 'javascript']
>>> a, b, c = s.split(",")
>>> a
'python'
>>> b
'jquery'
>>> c
'javascript'

Example 2: extract the domain name components

>>> s = 'irc.freenode.net'
>>> subdomain, domain, tld = s.split('.')
>>> subdomain
'irc'
>>> domain
'freenode'
>>> tld
'net'

Example 3: extract the domain name

>>> s = 'irc.freenode.net'
>>> i = s.split('.', 1)
>>> domain_name = i[1]
>>> domain_name
'freenode.net'

Example 4: sing a song

lyrics = 'one! two! three! four!'
nums = lyrics.split(' ', 2)
for num in nums:
  print 'I say ' + num

So that's it. Splitting a string in Python is really easy, all you have to do is call the split method on a string object and pass the delimiter and optional maxsplit count.

Notes#

  1. Arrays in Python are an altogether different beast compared to PHP or JavaScript.
  2. Lists are are Pythons 'arrays', if you want an equivalent to the data type found in PHP or JavaScript.

Exercise#

  1. How do you split 1234567890 into individual numbers?
  2. How do you split abcdef into individual characters?
  3. How do you split ag373jjsl?
  4. Is your method the best? Really? Can you make it better?
  5. How do you create a string from a list?
  6. How do you create a string from a tuple?
  7. What is the difference between array and list?
  8. What is the difference between array and tuple?

References#

  1. Python - list
  2. Python - tuple
  3. Python - string methods
  4. Python - array