Skip to content

Python string contains character

  • by

The easiest way to check if a Python string contains a character is to use the in operator. It returns a Boolean (either True or False)

Python string contains the character

Simple example code.

s = "Hello"
c = "H"

if c in s:
    print("Found!")
else:
    print("Not found!")

Output:

Python string contains the character

Check if the string contains specific characters in a text file

ser = open("hello.txt", "rb")
s = ser.read(1000) 
if "developer" in s:
  print("True")
else:
  print("False")
ser.close()

Just change ‘rb’ in ‘r’ (or do not put anything, it will be ‘r’ as default). A better way to open a file is this

with open("hello.txt", "r", encoding='utf-8') as ser:
    s = ser.read(1000) 
    if "developer" in s:
        print("True")
    else:
        print("False")

Using a if ... in statement. We can do this as follows:

if 'apples' in 'This string has apples':
    print('Apples in string')
else:
    print('Apples not in string')

Do comment if you have any doubts or suggestions on this Python string topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading