How to Check If a String Contains a Character in Python

To check if a string contains a character in Python, you can use the in operator or the index() function.

The following examples show how to check if a string contains a character in Python.

Using in Operator

We can use the in operator to check if a string contains a character.

Suppose we have the following string:

# Declare string
string = "Anita"

# Check if the character is present
if "a" in string:
    print("The string contains the character.")
else:
    print("The string does not contain the character.")

Output: 👇️

The string contains the character.

In this example, we use the in operator to check if the character “a” is present in the string string.

Using index() Function

We can use the index() function to check if a string contains a character.

Suppose we have the following string:

# Declare string
string = "Anita"

# Check if the character is present
try:
    string.index("a")
    print("The string contains the character.")
except ValueError:
    print("The string does not contain the character.")

Output: 👇️

The string contains the character.

In this example, we use the index() function to check if the character “a” is present in the string string. If the character is found, the function returns its index; otherwise, it raises a ValueError.

Conclusion

We can use the in operator and the index() function to check if a string contains a character in Python.