python
Python - Get first word form a string
If you have a python string and you want to get the very first word from that string, you can use the below code.
my_str = "Hello World"
first_word = my_str.split(' ', 1)[0]
print(first_word)
# -> Hello
Output
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(' ')[0]
print(result)
Output
Programming
my_str = "Hello World"
first_word = my_str.partition(' ')[0]
print(first_word)
# -> Hello
In the above code, we are getting the first word using the partition() method. We are passing the space separator to the method and getting the first-word using index 0.
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
The above code example will return the first word in the first_word variable and the rest of the words in the rest_of_the_words variable.
Was this helpful?
Similar Posts
- Python - String , Check If Word Is In string
- Python code to get the first character from a string
- Get first n words from a string in Python
- Get first N characters from a string in Python
- Capitalize first letter of a string in Python (5 Solutions)
- Get first record Sqlalchemy
- First highest views based recommendation system in python part 1