Print Nth word in a given string in Python

In this tutorial, we will see how can we find Nth word in a given string in Python.
Often we come across situations where we don’t want the entire string but only a particular word from that string.
For example.
Suppose we want to know what is the most common last name in our class, school or company. In this case, we don’t need the complete name (First Name + Last Name) of a person, we only need his last name to find out the most common name.

So, let’s see how can we extract it from a given string.

Using loops: Print Nth word in a given string

The word we are looking for is after N-1th space. We use ‘count’ to keep track of spaces.

def findword(name,n):
    #To keep track of word
    count=0
    #To store the required word
    required_word=""
    for i in name:
        if i==" ":
            count+=1
            if count==n:
                break
            required_word=""
        else:
            required_word+=i
    print("Required word is:",required_word)

#given string
name="Vikram Singh Rathode"
#Nth word of the string
n=3
findword(name,n)
    
OUTPUT:
Required word is: Rathode

Method 2: using split() function

Split function breaks a string into substrings if it finds the specified separator. It makes a list of the substrings. So, if we use ‘ ‘ as a separator we can obtain a list of all the words.

def findword(name,n):
    #Using ' ' as a separator, All_words ia a list of all the words in the String
    All_words=name.split(" ")
    print("Required word is:",All_words[n-1])
    
name="Vikram Singh Rathode"
n=3
findword(name,n)
OUTPUT:
Required word is: Rathode

 

Also read:

Creating a Word Counter in Python

Find nth prime number in python

Leave a Reply

Your email address will not be published. Required fields are marked *