In Python, you can use the startswith () method of a string to check whether a string starts with a specified substring. Its syntax is as follows:
string.startswith(substring)
Where string is the string to be checked and substring is the substring to be checked. This method returns a Boolean value indicating whether the string starts with substring.
Here is an example:
string = "Hello, world!" if string.startswith("Hello"): print("The string starts with 'Hello'") else: print("The string does not start with 'Hello'")
The output result is:
The string starts with 'Hello'
In this example, we first define a string string, and then use the startswith () method to check whether it starts with the substring "Hello". Since string really starts with "Hello", the program will output corresponding prompt information.
It should be noted that the startswith() method can also accept a tuple as a parameter to check whether the string starts with any substring in the tuple. For example:
string = "Hello, world!" if string.startswith(("Hello", "Hi")): print("The string starts with 'Hello' or 'Hi'") else: print("The string does not start with 'Hello' or 'Hi'")
The output result is:
The string starts with 'Hello' or 'Hi'
In this example, we pass a tuple containing two substrings to the startswith() method to check whether the string starts with "Hello" or "Hi". Since string really starts with "Hello", the program will output corresponding prompt information.
Scan the code to follow the official account
Get more news about webmaster circle!
Entrepreneurship, operation and new knowledge