Last modified: Jan 10, 2023 By Alexander Williams
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 </>