Does Python have a string 'contains' substring method?

 

Yes, Python provides a method to check if a string contains a substring. You can use the in keyword or the str.find() method to achieve this. Here's how:

  1. Using the in keyword: The in keyword can be used to check if a substring is present in a string. It returns a Boolean value (True or False).

    python
  • main_string = "Hello, World!" substring = "World" if substring in main_string: print("Substring found") else: print("Substring not found")
  • Using the str.find() method: The str.find() method returns the index of the first occurrence of the substring, or -1 if the substring is not found.

    python
    1. main_string = "Hello, World!" substring = "World" index = main_string.find(substring) if index != -1: print(f"Substring found at index {index}") else: print("Substring not found")

    Both methods are effective for checking whether a substring exists within a string. Use the method that best fits your code's context and desired behavior.

    Comments