Python: Get First, Second, Last word in String

Python: Get First, Second, Last word in String

To get a word in a string by position in Python, we need to use split() to convert a string to a list and get any word by position using the index.

Get the first word in a string

To get the first word in a string, we need to split the string by whitespace. Then get the first word in the list by using the index [0].

my_string = "Hello Python Programming Language" # 👉️ String

split_str = my_string.split(" ") # 👉️ Split String by Whitespace

f_word = split_str[0] # 👉️ Get The Fisrt Word

print(f_word) # 👉 Print

Output:

Hello

Get the second word in a string

To get the second word in a string, we need to split the string by whitespace. Then get the second word in the list using the index [1].

my_string = "Hello Python Programming Language" # 👉️ String

split_str = my_string.split(" ") # 👉️ Split String by Whitespace

s_word = split_str[1] # 👉️ Get The Second Word

print(s_word) # 👉 Print

Output:

Python

Get the third word in a string

To get the third word in a string, we need to split the string by whitespace. Then get the third word in the list using the index [2].

my_string = "Hello Python Programming Language" # 👉️ String

split_str = my_string.split(" ") # 👉️ Split String by Whitespace

t_word = split_str[2] # 👉️ Get The Third Word

print(t_word) # 👉 Print

Output:

Programming

Get the Last word in a string

To get the last word in a string, we need to split the string by whitespace. Then get the last word in the list by using the index [-1].

my_string = "Hello Python Programming Language" # 👉️ String

split_str = my_string.split(" ") # 👉️ Split String by Whitespac

l_word = split_str[-1] # 👉️ Get The Last Word

print(l_word) # 👉 Print

Output:

Language

The examples are available in the following video:

Happy Coding </>