Python string Contain

0 Shares
0
0
0
0

Introduction

Python's string class has a __contains__() function that we can use to check whether it contains another string or not.

Python string contain() method

The Python string __contains__() is an instance method and returns a boolean value of True or False depending on whether the string object contains the specified string object. Note that the Python string contain() method is case sensitive. Let's look at a simple example of the string __contains__() method.

s = 'abc'
print('s contains a =', s.__contains__('a'))
print('s contains A =', s.__contains__('A'))
print('s contains X =', s.__contains__('X'))

Output:

s contains a = True
s contains A = False
s contains X = False

We can also use the __contains__() function as a method of the str class.

print(str.__contains__('ABC', 'A'))
print(str.__contains__('ABC', 'D'))

Output:

True
False

Check if Python string contains substring

Let's look at another example where we ask the user to enter both strings and check if the first string contains a string or substring of the second string.

input_str1 = input('Please enter first input string\n')
input_str2 = input('Please enter second input string\n')
print('First Input String Contains Second String? ', input_str1.__contains__(input_str2))
Output: Please enter first input string JournalDev is Nice Please enter second input string Dev First Input String Contains Second String? True
Leave a Reply

Your email address will not be published. Required fields are marked *


You May Also Like
ai-tool-comparison-which-is-more-powerful-chatgpt-vs-grok

Comparison of ChatGPT 5.1 and Grok 4.1 AI tools: Which is more powerful?

In recent years, conversational AI (Chatbots) have become key tools for content creation, technical assistance, training, and many other uses on the web. Two prominent and up-to-date examples of these tools are ChatGPT-5.1 and Grok 4.1. But which one is really better for everyday use, technical projects, or creative ones? In this article, we’ll take a closer look at the performance, strengths, weaknesses, and suggested uses of both to help you make a better decision.
Amazon Elastic Compute Cloud

Amazon EC2 (Elastic Compute Cloud) — Expert Guide for Developers and Engineers

In the era of digital transformation, cloud infrastructure is the main pillar of enterprise technology support. Amazon EC2 or Elastic Compute Cloud is a key pillar of the AWS ecosystem, allowing you to deploy virtual servers with flexibility, scalability, and complete control. In this article, we will provide an in-depth explanation of the service, technical features, instance models, best practices, and purchasing the service.