Case sensitive
The simplest way to check whether there is a substring in a string is by using the in operator.
if "text" in "Just a simple text.":
print(True)
else:
print(False)
output
True
It returns True because “text” is contained in the “Just a simple text” string. When you change the case in the text, it will return False. Look at these examples.
if "Text" in "Just a simple text.":
print(True)
else:
print(False)
and
if "text" in "Just a simple Text.":
print(True)
else:
print(False)
They both return False because there are different case sizes.
Ignore case
If you want to create a case-insensitive script, you can use the lower function. It will cast all characters in a string to lowercase.
my_string = "Just a simple text."
if my_substring.lower() in my_string.lower():
print(True)
else:
print(False)
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.
my_string = "this is a text"
if my_string.startswith("this"):
print(True)
else:
print(False)
This code returns True.
my_string = " this is a text"
if my_string.startswith("this"):
print(True)
else:
print(False)
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.
my_string = 'This is a text'
if my_string.endswith("text"):
print(True)
else:
print(False)
Count how many times a substring is present in a string
my_string1 = "is a text in a text"
my_string2 = "Just a normal string"
print(my_string1.count("text"))
print(my_string2.count("text"))
The script returns the following output.
2 0
Get a substring position
In order to check the position of the string, use the index function.
my_string = "This is a text"
print(my_string.index("is"))
output
2
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.