String contains a substring in Python

case sensitive

The simplest way to check whether there is a substring in a string is by using the in operator.

output

It returns True because “text” is contained in the “Just a simple text” string. When you change case in the text, it will return False. Look at these examples.

and

They both return False because there are different case sizes.

ignore case

If you want to create the case-insensitive script, you can use the lower function. It will cast all characters in a string to lowercase.

The output this time is True.

starts with

With the startswith function, you can check whether the string starts with the chosen substring. This code is case sensitive.

This code returns True.

This code returns False if there is a single character before the substring – even space.

ends with

This function is similar to the endswith function. It returns True each time there is a substring at the end of the string.

count how many times a substring is present in a string

The script returns the following output.

get a substring position

In order to check the position of the string, use the index function.

output

The index function shows the first occurrence of the given string. In this example, the first is inside the word This. Counting starts at 0, so the number is 2.