How to Check if a String Starts or Ends with a Specific Substring
How to Check if a String Starts or Ends with a Specific Substring
How to Check if a String Starts or Ends with a Specific Substring
I have a string and I need to determine if it starts or ends with a particular substring. How can I do this in Python?
solveurit24@gmail.com Changed status to publish February 16, 2025
In Python, you can use the str.startswith() and str.endswith() methods to check if a string begins or ends with a specific substring.
Code Example:
def check_string(s, start_sub, end_sub):
starts = s.startswith(start_sub)
ends = s.endswith(end_sub)
return starts, ends
# Example usage
sentence = "Hello, world!"
print(check_string(sentence, "Hello", "world!")) # Output: (True, True)This function returns True if the string starts with the given substring and True if it ends with the specified substring.
solveurit24@gmail.com Changed status to publish February 16, 2025