How to get the last word from a string in Python?
In this tutorial, I’ll discuss how you can get the last word from a given string in Python. It’s very easy to get the last word from a given string in Python. To get the last word from a string, we have to convert the string into a list at the first. After converting the string into a list, simply we can use the slicing operator to get the last word of the string and then we can print it. For converting a string into a list we can simply use the split() method.
Separator: This is optional. This is used to specify where we want to split the string. By default, it takes whitespace as a separator.
Maxsplit : This is also optional. This is used to specify how many splits we want to do in the given string. By default, it takes the value as -1, which means all the occurrences or no limit on the number of splits.
Now, let me give an example to understand the concept
#taking input from the user string = input("Enter your string: ") #splitting the string words = string.split() #slicing the list (negative index means index from the end) #-1 means the last element of the list print(words[-1])
Enter your string: Welcome to Codespeedy Codespeedy
In this above code, I gave the input as ‘Welcome to Codespeedy’ and it gave me output as ‘Codespeedy’ that is the last word of the string.
So I hope now you’re familiar with the concept of how you can get the last word from a string.