String startswith() Method in Python

Python String startswith() Method

The startswith() method in Python is a built-in string method that allows you to check if a string starts with a specific prefix. It returns True if the string starts with the given prefix, otherwise, it returns False. The basic syntax of the startswith() method is as follows:

string.startswith(prefix, start, end)

Parameters:

  • prefix: This is the prefix or substring that you want to check if the string starts with.
  • start (optional): The start index from where the search should begin. By default, it is 0 (the beginning of the string).
  • end (optional): The end index where the search should stop. The startswith() method only considers characters up to this index but does not include the character at the end index. By default, it considers the whole string.

Return value:

  • True: If the string starts with the specified prefix.
  • False: If the string does not start with the specified prefix.

Here are some examples of using the startswith() method:

text = "Hello, world!"

# Check if the string starts with "Hello"
result1 = text.startswith("Hello")
print(result1)  # Output: True

# Check if the string starts with "hello" (case-sensitive)
result2 = text.startswith("hello")
print(result2)  # Output: False

# Check if the string starts with "Hello" from index 0 to 5 (exclusive)
result3 = text.startswith("Hello", 0, 5)
print(result3)  # Output: True

# Check if the string starts with "world" from index 7 to the end
result4 = text.startswith("world", 7)
print(result4)  # Output: True

Keep in mind that the startswith() method is case-sensitive. If you need a case-insensitive check, you can convert both the string and the prefix to lowercase (or uppercase) using the lower() (or upper()) method before calling startswith().