In this tutorial, we will learn how to get the second word in a string using Python.
Steps:
1. First, we need to split the string into a list of words using the split()
method. This method breaks the string into words wherever it finds whitespaces.
2. Next, we can use indexing and list slicing to return the second word from the list.
Here’s the code to do so:
1 2 3 4 5 6 7 8 9 10 11 |
# Sample string string = "Hello World! How are you?" # Split string into words words_list = string.split() # Get the second word second_word = words_list[1] # Print the second word print(second_word) |
The output of the above code will be:
'World!'
Explanation:
We defined a string called string
with the value “Hello World! How are you?”. Next, we used the split()
method to split the string into words and store them in a list called words_list
. Using indexing and list slicing, we retrieved the second word (which has index 1) from the words_list
. Finally, we printed the second word using the print()
function.
In conclusion, getting the second word of a string in Python can be done by splitting the string into words using the split()
method and then accessing the second word using indexing and list slicing.
Full code:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Sample string string = "Hello World! How are you?" # Split string into words words_list = string.split() # Get the second word second_word = words_list[1] # Print the second word print(second_word) |
Output:
'World!'