In Python, we can easily get the first word in a string. To do so, we can use the Python split() function and then access the first element of the list of words.
string = "This is a string with words."
first_word = string.split(" ")[0]
#Output:
This
When working with strings in our Python code, it can be useful to be able to extract specific words from the string variables.
In particular, it would be useful to be able to get the first word from a string of words.
With Python, we can easily get the first word from a string.
The easiest way to get the first word from a string in Python is to use the Python split() function, and then access the first element (position “0”).
Below shows an example of how to get the first word in a string using Python.
string = "This is a string with words."
first_word = string.split(" ")[0]
#Output:
This
How to Get the Last Word of a String
In a very similar way to above, we can also get the last word of a string.
The difference between getting the first and last word in a string is that now we will be getting the last element after splitting the original string.
To get the last word from a string, we use the Python split() function and then access the “-1” position element.
Below is an example of how you can get the last word in a string using Python.
string = "This is a string with words."
last_word = string.split(" ")[-1]
#Output:
words.
Hopefully this article has been useful for you to understand how to get the first word of a string in Python.