Чтобы проверить, начинается ли строка с определенной подстроки в Python, вы можете использовать различные методы. Вот несколько примеров:
-
Использование метода
startswith():string = "Hello, world!" substring = "Hello" if string.startswith(substring): print("The string starts with the given substring.") else: print("The string does not start with the given substring.") -
Использование нарезки и сравнения:
string = "Hello, world!" substring = "Hello" if string[:len(substring)] == substring: print("The string starts with the given substring.") else: print("The string does not start with the given substring.") -
Использование регулярных выражений с модулем
re:import re string = "Hello, world!" substring = "Hello" if re.match(f"^{re.escape(substring)}", string): print("The string starts with the given substring.") else: print("The string does not start with the given substring.")