String split methods

Sometimes we see strings in the form of parts such as "27-12-2016" and "Mohit raj". Our requirement is to get the last part or first part. So, based upon delimiters, we can split strings into parts and take the desirable part. Let's understand how it works; from the first string, we need only the year part.

We have an interesting method called split().

The syntax for the method is given as follows:

Str1.split(“delimiter”, num)

Let's look at an example:

>>> str1.split("-", 1)
['27', '12-2016']
>>>

The split method returns a list of all the words of the string separated by a delimiter and the num integer specifies the maximum splits. If num is not specified, then all the possible splits are made. Refer to the following example:

>>> str1 = "27-12-2016"
>>> str1.split("-")
['27', '12', '2016']
>>>

So far, we have not learned about lists, which we will be covering later. But using this method, we can access a particular value of the list:

>>> list1 = str1.split("-")
>>> list1[2]
'2016'
>>>

If you don't provide any delimiter, then the space is taken as the default, as shown here:

>>> name = "Mohit raj"
>>> name.split()
['Mohit', 'raj']
>>>

If you want that splits should be started from the right, then you can use the rsplit() method, as shown in the following example:

>>> str1 = "27-12-2016"
>>> str1.rsplit("-", 1)
['27-12', '2016']
>>>

I hope you got the idea of splitting.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.114.85