Python provides several ways to check if a given sentence starts with a certain word. The most straightforward approach is using the startswith() method. Examples:
Using python built-in function startswith()
This function takes in two arguments, a string and an optional flag that checks for case sensitivity, which defaults to False. If the sentence begins with the specified word, true will be returned; otherwise, false will be returned. For example, to check if a sentence starts with the word "Hello", we can use the following code:
sentence = "Hello How are you today ?"
sentence.startswith('Hello')
output of the above code is
True
While
sentence.startswith('Hi')
returns
False
Using startswith() with a if statement
if sentence.startswith('Hello'):
print("Sentence Starts With 'Hello'")
returns
"Sentence Starts With 'Hello'
Using regular expressions
Alternatively, we can use regular expressions to match the start of a sentence. To do this, we can use the re.match() function which takes in two arguments, a regex pattern and the string to be matched. For example:
import re
sentence = "Hello How are you today ?"
if re.match('Hello', sentence):
print("Sentence Starts With 'Hello'")
output
Sentence Starts With 'Hello'
Note that it is case sensitive
if re.match('hello', sentence):
print("Sentence Starts With 'hello'")
returns nothing
Using find
Finally, we can also use the find() method with a start parameter to look for the first occurrence of a word in the sentence. For example:
sentence = "Hello How are you today ?"
if sentence.find('Hello', 0) == 0:
print("Sentence Starts With 'Hello'")
output
Sentence Starts With 'Hello'
References
Links | Site |
---|---|
startswith() | docs.python.org |
regular expressions | docs.python.org |
find() | docs.python.org |