Sometimes we come across situations where we need to get first word in string python. Hence it is often helpful to have shorthands to perform this function. This article also covers the situations where we need all words present in the string.
Method #1: Using split()
Using the split function, we can break the string into a list of words. Use str.split() and list indexing to get the first word in a string. Call str.split() to create a list of all words in str separated by space or newline character. Index the result of str.split() with [0] to return the first word in str.
Get first word in string Python
Getting the first word in a string will return the first series of characters that precede a space or a newline character. For example, getting the first word in the “Tutorials Website” string returns “Tutorials.”
2 3 4 5 6 7 |
string = "Tutorials Website" all_words = string.split() first_word= all_words[0] print(first_word) |
Output:
2 3 4 |
Tutorials |
Get the All words in a string
Getting all words in a string will return the series of characters that precede a space or a newline character. For example,
2 3 4 5 6 |
string = "Tutorials Website is the best Online Web Development Tutorials Portal" all_words = string.split() print(all_words) |
Output:
2 3 4 |
['Tutorials', 'Website', 'is', 'the', 'best', 'Online', 'Web', 'Development', 'Tutorials', 'Portal'] |
Read Also: Python vs Node.JS: Which one is the best fit for your project?
Conclusion:
Using the Split function to Get first word in string python is the most generic and recommended method to perform this particular task. But the drawback is that it fails to contain punctuation marks in string cases.
Pradeep Maurya is the Professional Web Developer & Designer and the Founder of “Tutorials website”. He lives in Delhi and loves to be a self-dependent person. As an owner, he is trying his best to improve this platform day by day. His passion, dedication and quick decision making ability to stand apart from others. He’s an avid blogger and writes on the publications like Dzone, e27.co