如何使用Python获取给定字符串中的第N个单词?

如何使用Python获取给定字符串中的第N个单词?

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.

方法1:字符串分割

这种方法涉及将字符串分割为单词列表,并根据索引访问所需的单词。

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.

算法

  • Accept the input string and the value of N.

  • 使用split()方法将字符串拆分为单词列表。

  • Access the Nth word from the list using indexing.

  • Access the Nth word from the list using indexing.

Example

让我们考虑以下字符串:"The quick brown fox jumps over the lazy dog." 在下面的示例中,输入字符串使用split()方法分割成一个单词列表。由于N的值为3,函数返回第三个单词,"brown"。

def get_nth_word_split(string, n):
words = string.split()
if 1