Python – Get Nth word in given String

Sometimes, while working with data, we can have a problem in which we need to get the Nth word of a String. This kind of problem has many application in school and day-day programming. Let’s discuss certain ways in which this problem can be solved.

Method #1 : Using loop
This is one way in which this problem can be solved. In this, we run a loop and check for spaces. The Nth word is when there is N-1th space. We return that word.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Get Nth word in String
# using loop
  
# initializing string 
test_str = "GFG is for Geeks"
  
# printing original string 
print("The original string is : " + test_str)
  
# initializing N 
N = 3
  
# Get Nth word in String
# using loop
count = 0
res = ""
for ele in test_str:
    if ele == ' ':
        count = count + 1
        if count == N:
            break
        res = ""
    else :
        res = res + ele
  
# printing result
print("The Nth word in String : " + res)

chevron_right


Output :



The original string is : GFG is for Geeks
The Nth word in String : for

 

Method #2 : Using split()
This is a shorthand with the help of which this problem can be solved. In this, we split the string into a list and then return the Nth occurring element.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Get Nth word in String
# using split()
  
# initializing string 
test_str = "GFG is for Geeks"
  
# printing original string 
print("The original string is : " + test_str)
  
# initializing N 
N = 3
  
# Get Nth word in String
# using split()
res = test_str.split(' ')[N-1]
  
# printing result
print("The Nth word in String : " + res)

chevron_right


Output :

The original string is : GFG is for Geeks
The Nth word in String : for


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.