my_str = "Hello World" first_word = my_str.split(' ', 1) print(first_word) # -> Hello
We are using the .split() method of python string here. First, we are splitting the string using spaces between the words then we are getting the first-word using index 0.
You can also write the above code example as below:
my_str = "Programming is fun" result = my_str.split(' ') print(result)
my_str = "Hello World" first_word = my_str.partition(' ') print(first_word) # -> Hello
str_1 = "Programming is cool" (first_word, rest_of_the_words) = str_1.split(maxsplit=1) print(first_word) # -> Programming print(rest_of_the_words) # -> is cool