- How to get the last word from a string in Python?
- 2 responses to “How to get the last word from a string in Python?”
- Extract a specific word from a string in Python
- Extract a specific word from a string using string slicing in python
- Extract a specific word from a string using find() method.
- Using index() method.
- Using regular expressions to extract any specific word
- Conclusion
- How to get the first word in a string Python
- Method #1: Using split()
- Get first word in string Python
- Output:
- Get the All words in a string
- Output:
- Conclusion:
- You May Also Like:
- Related posts
- Why WebAssembly is the Future of Browser-Based Python Development
- Create WooCommerce custom product type programmatically
- Mars vs Python: What is the Best Programming Language?
- Over 2,50,000+ Readers
- Download Our Android APP
- Mini Projects
- I am looking for .
- Popular Topics
- Explore Tags Cloud
- About Tutorials Website
- Customer Area
- Quick Links
- Privacy Overview
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.
your_string.split(Separator, Maxsplit)
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.
2 responses to “How to get the last word from a string in Python?”
Thank you very very much… Whoever is reading this comment I want to tell you that this method works. You should try…
Extract a specific word from a string in Python
While handling text data, sometimes we have to search for occurrences of specific words in the text and extract specific words. In this tutorial, we will learn about different methods to extract a specific word from a string in python using inbuilt string methods and regular expressions.So, let’s dive into it.
Extract a specific word from a string using string slicing in python
If we know the exact position of the word to be extracted from the string, we can perform slicing operation on the string to extract the desired word from the string as shown below.
search_string= "I am a python programmer and I am writing this code for pythonforbeginners.com" print("String from which word has to be searched is:") print(search_string) print("word to be extracted from string:") word="writing" print(word) #calculate length of the word lword=len(word) #suppose we already know the starting index of word writing i.e. 34 extracted_string= search_string[34:34+lword] print("Extracted word is:") print(extracted_string)
String from which word has to be searched is: I am a python programmer and I am writing this code for pythonforbeginners.com word to be extracted from string: writing Extracted word is: writing
Extract a specific word from a string using find() method.
If we want to extract a specific word from the string and we do not know the exact position of the word, we can first find the position of the word using find() method and then we can extract the word using string slicing.
The find() method when invoked on any string, takes the string to be searched as a parameter and gives as output the position of first occurrence of the input string which was to be searched. If the string to be searched is not present, the find() method returns -1.
After finding the position of the word to be extracted with find() method, we can simply extract it using slice operation as follows.
search_string= "I am a python programmer and I am writing this code for pythonforbeginners.com" print("String from which word has to be searched is:") print(search_string) print("word to be extracted from string:") word="writing" print(word) #calculate length of the word lword=len(word) start_index=search_string.find(word) print("start index of the word in string is:") print(start_index) extracted_string= search_string[start_index:start_index+lword] print("Extracted word is:") print(extracted_string)
String from which word has to be searched is: I am a python programmer and I am writing this code for pythonforbeginners.com word to be extracted from string: writing start index of the word in string is: 34 Extracted word is: writing
Using index() method.
If we don’t know the exact position of the word to be extracted,we can also use string index() method to find out the exact position of the word and then we can use slicing to extract the word.
The index() method when invoked on any string, takes the string to be searched as a parameter and gives as output the position of first occurrence of the input string which was to be searched. If the string to be searched is not present, index() throws an exception. For this reason we will have to use python try except to handle the exceptions while using index() method.
We can extract a specific word from a string in python using index() method and string slicing as follows.
search_string= "I am a python programmer and I am writing this code for pythonforbeginners.com" print("String from which word has to be searched is:") print(search_string) print("word to be extracted from string:") word="writing" print(word) #calculate length of the word lword=len(word) try: start_index=search_string.index(word) print("start index of the word in string is:") print(start_index) extracted_string= search_string[start_index:start_index+lword] print("Extracted word is:") print(extracted_string) except: print("word not found")
String from which word has to be searched is: I am a python programmer and I am writing this code for pythonforbeginners.com word to be extracted from string: writing start index of the word in string is: 34 Extracted word is: writing
Using regular expressions to extract any specific word
We can use regular expressions in python to extract specific words from a string. We can use search() method from re module to find the first occurrence of the word and then we can obtain the word using slicing.
re.search() method will take the word to be extracted in regular expression form and the string as input and and returns a re.MatchObject which contains the starting and ending index of the word.If the given word is not found, re.search() will return None . After getting the indices of the word to be extracted, we can extract it using string slicing as shown below.
import re search_string= "I am a python programmer and I am writing this code for pythonforbeginners.com" print("String from which word has to be searched is:") print(search_string) print("word to be extracted from string:") word=r"writing" print(word) #calculate length of the word lword=len(word) start_index=re.search(word,search_string).start() print("start index of the word in string is:") print(start_index) extracted_string= search_string[start_index:start_index+lword] print("Extracted word is:") print(extracted_string)
String from which word has to be searched is: I am a python programmer and I am writing this code for pythonforbeginners.com word to be extracted from string: writing start index of the word in string is: 34 Extracted word is: writing
Conclusion
In this article, we have seen how to find any specific word in a string using different string methods and regular expressions and then print the word using string slicing in python. We can also use python string split operation when we just have to search if the word is present or not, given that words are space separated. Stay tuned for more informative articles.
How to get the first word in a string Python
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.”
Output:
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,
Output:
[ ‘Tutorials’ , ‘Website’ , ‘is’ , ‘the’ , ‘best’ , ‘Online’ , ‘Web’ , ‘Development’ , ‘Tutorials’ , ‘Portal’ ]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
You May Also Like:
Related posts
Why WebAssembly is the Future of Browser-Based Python Development
Introduction Every single programmer needs to have access to a reliable programming environment. It does not.
Create WooCommerce custom product type programmatically
Mars vs Python: What is the Best Programming Language?
What is Python? Python is a high-level, interpreted programming language that provides users with an interactive.
Over 2,50,000+ Readers
Get the fresh articles related to programming and digital marketing from Tutorialswebsite
Download Our Android APP
Mini Projects
I am looking for .
Popular Topics
Explore Tags Cloud
About Tutorials Website
Tutorials Website is a free online resource on programming and digital marketing for beginners. It was founded in Jan 2016 by Pradeep Maurya to deliver the best and fresh articles for students and our readers to skill up as they would like to.
Customer Area
Quick Links
© Copyright 2016-23, Tutorialswebsite.com. All rights reserved
This website uses cookies to improve your experience. We’ll assume you’re ok with this, but you can opt-out if you wish. Cookie settingsACCEPT
Privacy Overview
This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.