Python: Split string method and examples
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#
- Arrays in Python are an altogether different beast compared to PHP or JavaScript.
- Lists are are Pythons 'arrays', if you want an equivalent to the data type found in PHP or JavaScript.
Exercise#
- How do you split 1234567890 into individual numbers?
- How do you split abcdef into individual characters?
- How do you split ag373jjsl?
- Is your method the best? Really? Can you make it better?
- How do you create a string from a
list
? - How do you create a string from a
tuple
? - What is the difference between
array
andlist
? - What is the difference between
array
andtuple
?
References#
- Python - list
- Python - tuple
- Python - string methods
- Python - array