15. Partition

It partitions a string into 3 parts and returns a tuple that contains these parts.

txt = "Python is awesome!"
('Python ', 'is', ' awesome!')
txt = "Python is awesome and it is easy to learn."
('Python is awesome ', 'and', ' it is easy to learn.')

The partition method returns exactly 3 parts. If there are multiple occurrences of the character used for partitioning, the first one is taken into account.

txt = "Python and data science and machine learning"
('Python ', 'and', ' data science and machine learning')

We can also do a similar operation with the split method by limiting the number of splits. However, there are some differences.

  • The split method returns a list
  • The returned list does not include the characters used for splitting
txt = "Python and data science and machine learning"
txt.split("and", 1)
['Python ', ' data science and machine learning']

Continue reading: https://towardsdatascience.com/15-must-know-python-string-methods-64a4f554941b?source=rss—-7f60cf5620c9—4

Source: towardsdatascience.com