How to Get the Nth Word in a Given String using Python?

Extracting specific words from a string is a common programming task. Python provides several approaches to get the Nth word from a string, including split() method, regular expressions, and custom delimiters.

Using split() Method

The simplest approach is splitting the string into words and accessing by index ?

Syntax

words = string.split()
nth_word = words[n-1]  # n is 1-based index

Example

def get_nth_word_split(string, n):
    words = string.split()
    if 1 <= n <= len(words):
        return words[n-1]
    else:
        return "Invalid value of N."

# Test the function
input_string = "The quick brown fox jumps over the lazy dog."
n = 3
result = get_nth_word_split(input_string, n)
print(f"The {n}rd word is: {result}")
The 3rd word is: brown

Using Regular Expressions

Regular expressions provide more control over word matching patterns ?

Syntax

import re
words = re.findall(pattern, string)

Example

import re

def get_nth_word_regex(string, n):
    pattern = r'\w+'
    words = re.findall(pattern, string)
    if 1 <= n <= len(words):
        return words[n-1]
    else:
        return "Invalid value of N."

# Test the function
input_string = "The quick brown fox jumps over the lazy dog."
n = 4
result = get_nth_word_regex(input_string, n)
print(f"The {n}th word is: {result}")
The 4th word is: fox

Using Custom Delimiter

When words are separated by specific characters other than whitespace ?

Example

def get_nth_word_custom_delimiter(string, delimiter, n):
    words = string.split(delimiter)
    if 1 <= n <= len(words):
        return words[n-1].strip()  # Remove any extra whitespace
    else:
        return "Invalid value of N."

# Test the function
input_string = "apple,banana,orange,mango"
delimiter = ","
n = 2
result = get_nth_word_custom_delimiter(input_string, delimiter, n)
print(f"The {n}nd word is: {result}")
The 2nd word is: banana

Comparison of Methods

Method Best For Handles Punctuation Performance
split() Simple whitespace-separated words No Fast
Regular expressions Complex word patterns Yes Slower
Custom delimiter Specific separators Depends on delimiter Fast

Error Handling Example

def get_nth_word_safe(string, n):
    """Get nth word with comprehensive error handling"""
    if not string or not string.strip():
        return "Empty string provided."
    
    words = string.split()
    if n < 1:
        return "N must be a positive integer."
    elif n > len(words):
        return f"String has only {len(words)} words."
    else:
        return words[n-1]

# Test with different scenarios
test_cases = [
    ("Hello world Python", 2),
    ("Single", 1),
    ("", 1),
    ("One two three", 5)
]

for text, n in test_cases:
    result = get_nth_word_safe(text, n)
    print(f"String: '{text}', N={n} ? {result}")
String: 'Hello world Python', N=2 ? world
String: 'Single', N=1 ? Single
String: '', N=1 ? Empty string provided.
String: 'One two three', N=5 ? String has only 3 words.

Conclusion

Use split() for simple whitespace-separated strings, regular expressions for complex patterns, and custom delimiters for specific separators. Always include error handling to manage edge cases like empty strings or invalid indices.

Updated on: 2026-03-27T08:35:39+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements