Write a Python program as function that checks whether a given string ‘s’ starts with another string ‘s1’, without using the built-in startswith() method.
def starts_with(s: str, s1: str) -> bool: """ checks if s is at least as long as s1, and if not, it immediately returns False since s1 cannot be a prefix of s """ if len(s1) > len(s): return False """ Next, it iterates through the characters of s1 using a loop and compares them to the corresponding characters in s. If any of these characters differ, the function returns False, indicating that s does not start with s1. """ for i in range(len(s1)): if s[i] != s1[i]: return False return True # Example of use of this function s = "Python Programmin" s1 = "Pyth" print(starts_with(s, s1)) # Output: True s2 = "Java" print(starts_with(s, s2)) # Output: False
One thought on “Solution Exercise 67: python algorithm to check if a given string start with an other string”
[…] Exercise 67 * || Solution […]