A Tip A Day — Python Tip #11: Split string using partition, rpartition & splitlines | Dev Skrol

Asha Ponraj
Analytics Vidhya
Published in
2 min readOct 16, 2021

--

Photo by Tania Melnyczuk on Unsplash

There are various ways to split strings.

The popular split function we use often is split(), rsplit()

Apart from these 3 there are a few more functions that is very useful in string manipulations.

The partition function splits the entire string into 3 parts and returns it as a tuple of 3 elements.

  1. The string before the separator
  2. The separator
  3. The string after the separator

This function splits only once and it will not split iteratively. So it splits at the first occurance of the separator.

Syntax:

string.partition(separator)

fullstring = "partition function is a type of split function in python." 
result = fullstring.partition("function")
print(result)
print(type(result))

Output:

('partition ', 'function', ' is a type of split function in python.') <class 'tuple'>

2. rpartition()

This function works similar to partition() except that it considers the last occurance of the separator.

fullstring = "partition function is a type of split function in python." 
result = fullstring.rpartition("function")
print(result)

Output:

('partition function is a type of split ', 'function', ' in python.')

3. splitlines()

This functions splits only by the line breaks.

This will not accept any separator, instead it will accept another optional boolean argument “keepends”.

If keepends is True then it will return the linebreak character along with the left part of the line breaks.

By default keepends is set to False.

fullstring = "partition function splits a string.\n This splits by separator.\n Returns tuple of 3 elements.\n Lets learn it." 
result = fullstring.splitlines()
print(result)

Output:

['partition function splits a string.', ' This splits by separator.', ' Returns tuple of 3 elements.', ' Lets learn it.']

Another example with keepends parameter:

result = fullstring.splitlines(keepends=True) 
print(result)
type(result)

Output:

['partition function splits a string.\n', ' This splits by separator.\n', ' Returns tuple of 3 elements.\n', ' Lets learn it.'] list

I hope you enjoyed learning various types of split functions in python.

Lets explore more about Python in future tips.

More interesting Python tips:

A Tip A Day — Python Tip #9: 3 Interesting things about format {}

A Tip A Day — Python Tip #6 — Pandas Merge

A Tip A Day — Python Tip #5 — Pandas Concat & Append All Other Tips

Other interesting concepts:

SpaCy Vs NLTK — Basic NLP Operations code and result comparison

Best way to Impute NAN within Groups — Mean & Mode

Originally published at https://devskrol.com on October 16, 2021.

--

--