You have probably seen cases when you can do splits of strings into multiple parts based on a pattern that is observed in the string. For example, let us say that we want to save all the words that are part of a sentence.
To do that, we usually try to do split the sentence into words based on the spaces that we find, such as:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Another example of this way of turning a string into a list of strings can be when doing the splitting using commas:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
What is not that much known is the fact that the method split() can actually take a second argument that indicates the number of occurrences after which the splitting should stop.
For example, let us say that in the previous example, we want only to do the split for the first 2 occurrences of the comma and then stop. To do that, we simply need to specify the number 2 as follows:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This is probably not the best example to illustrate its usefulness, but I believe it should help you understand that such a quick solution actually exists.
I am an experienced and passionate Senior Software Engineer with a demonstrated history of working in the full life cycle of software development with enormous curiosity for data science, machine learning, algorithms, data structures, and solving challenging problems. I am an open-source enthusiast at https://github.com/fatosmorina and also a writer.
I am open for new opportunities.