search
HomeBackend DevelopmentPython TutorialHow to get the Nth word in a given string using Python?

How to get the Nth word in a given string using Python?

We can get the Nth Word in a Given String in Python using string splitting, regular expressions, split() method, etc. Manipulating strings is a common task in programming, and extracting specific words from a string can be particularly useful in various scenarios. In this article, we will explore different methods to extract the Nth word from a given string using Python.

Method 1: String splitting

This method involves splitting the string into a list of words and accessing the desired word based on the index.

Syntax

words = string.split()

Here, the split() method splits the string based on whitespace by default. The resulting words are stored in the words list.

algorithm

  • Accept the input string and the value of N.

  • Use the split() method to split the string into a list of words.

  • Access the Nth word from the list using indexing.

  • Access the Nth word from the list using indexing.

Example

Let us consider the following string: "The quick brown fox jumps over the lazy dog." In the following example, the input string is split into a list of words using the split() method. Since the value of N is 3, the function returns the third word, "brown".

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
print(get_nth_word_split(input_string, n))

Output

brown

Method 2: Use regular expressions

Another method to extract the Nth word involves using regular expressions. This approach provides flexibility in handling different word patterns and delimiters.

Syntax

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

Here, use the re.findall() function from the re module to extract all words from the input string based on the specified pattern. Patterns are defined using regular expressions. The extracted words are stored in the words list.

algorithm

  • Import re module.

  • Accept the input string and the value of N.

  • Define a regular expression pattern to match words.

  • Use the findall() function from the re module to extract all words from the string.

  • Access the Nth word from the list obtained in step 4 using indexing.

  • Return the Nth word.

Example

In the following example, the regular expression pattern '\w' is used to match all words in the input string. The findall() function extracts all words and stores them in a list. Since the value of N is 4, the function returns the fourth word "jumps".

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
print(get_nth_word_regex(input_string, n))

Output

fox

Method 3: Use split() method and custom separator

In some cases, the string may have a specific delimiter other than whitespace. In such scenarios, we can modify the first method by specifying a custom delimiter for splitting the string.

Syntax

words = string.split(delimiter)

Here, the split() method is used to split the input string into a list of words based on a custom delimiter. The delimiter is passed as a parameter to the split() method. The split words are stored in the words list.

algorithm

  • Accept the input string, the delimiter, and the value of N.

  • Split the string into a list of words using the split() method and a custom delimiter.

  • Access the Nth word from the list using indexing

  • Return the Nth word.

Example

In the example below, the string is split into words using a custom delimiter (comma ","). The second word "banana" is extracted and returned because it corresponds to a value of N of 2.

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

# Test the function
input_string = "apple,banana,orange,mango"
delimiter = ","
n = 2
print(get_nth_word_custom_delimiter(input_string, delimiter, n))

Output

banana

Conclusion

In this article, we have discussed how to get the nth word in a given string with the help of splitting string, using regular expressions and using splitting method with custom delimiter. Each method provides flexibility based on the requirements of the task. By understanding and implementing these techniques, you can efficiently extract specific words from strings in your Python program.

The above is the detailed content of How to get the Nth word in a given string using Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

For loop and while loop in Python: What are the advantages of each?For loop and while loop in Python: What are the advantages of each?May 13, 2025 am 12:01 AM

Forloopsareadvantageousforknowniterationsandsequences,offeringsimplicityandreadability;whileloopsareidealfordynamicconditionsandunknowniterations,providingcontrolovertermination.1)Forloopsareperfectforiteratingoverlists,tuples,orstrings,directlyacces

Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.