I am Hack Sparrow
Captain of the Internets.

Python: split string method and examples

string split method and examples in Python

So you are looking to break up a string into smaller strings (in 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, it returns a list as the result (you really don't want to a Python array for this one) and here are some examples. Examples 1 to 3 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
>>> b
>>> c

Example 2: extract the domain name components

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

Example 3: extract the domain name

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

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.


  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.

  1. How do you split 1234567890 into individual numbwer? πŸ˜‰
  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?

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

11 Responses to “Python: split string method and examples”

  1. Yogesh Prasad says:

    The answer to the second exercise:
    number = β€œabcdef”
    numList = []
    print numList

Make a Comment