DEV Community

drasticcode
drasticcode

Posted on

How do I check if a string contains something in Python?

What does the python string carries?

Python string carries refers to what's protected in a python string.

It can be any substring, integer fee, character, the normal expression can be said as python string carries substring, python string carries an integer, python string carries character, python string carries regex (normal expression).

Why will we need to recognise what python string carries?
We want to recognise what python string carries due to the fact it can create hassle whilst executing the conditional statements; it's miles higher to apprehend it.

Python string carries sub-string

How may want to we recognise python string carries sub-string?
There are few techniques that you may comply with to recognise if python carries a sub-string or not.

*Methods are given below:
*

String carries
In-operator
Find
Index.
String carries
The string carries a integrated technique in python to recognise whether or not the python string carries any other string or not.

It will go back the Boolean fee as output whilst the string carries substring; then, it's going to show true. Otherwise, it's going to show false.

Let’s apprehend it with the assist of an example:

Example:

`#python string contains method

python string contains sub-string

my_str = "Hello Drastic code"

substring = "code"

if (my_str.contains(substring)):
print("String contains sub-string !")
else:
print("String does not contain sub-string")`

Output:

String contains sub-string !

Top comments (1)

Collapse
 
thilakraj1998 profile image
Thilakraj Devadiga • Edited

Hey @drasticcode

Your example with throw Attribute Error
Since string object has no 'contains' function

You can try following code below to correct it, which utilizes In-Operator to find the existence of the substring in
the main string.

Code:

my_str = "Hello Drastic code"
substring = "code"
if (substring in (my_str)):
    print("String contains sub-string !")
else:
    print("String does not contain sub-string")
Enter fullscreen mode Exit fullscreen mode