How to split string by a delimiter str in Python?


Python's String class has a method called split() which takes a delimiter as optional argument. Default delimiter for it is whitespace. You can use it in the following way:

>>> 'aa-ab-ca'.split('-')
['aa', 'ab', 'ca']
>>> 'abc mno rst'.split(' ')
['abc', 'mno', 'rst']

You can also use regex for this operation. The re.split method takes a delimiter regex and the string and returns the list. For example:

>>> import re
>>> re.split('-', 'aa-ab-ca')
['aa', 'ab', 'ca']
>>>re.split(' ', 'abc mno rst')
['abc', 'mno', 'rst']


raja
Published on 12-Dec-2017 11:26:38
Advertisements