25
loading...
This website collects cookies to deliver better user experience
find()
method is to verify if a string contains a substring or not. If the string contains a substring, it returns the starting index of the substring; else returns -1 if it cannot find a substring.word = 'Hello its a beautiful day'
# returns first occurrence of Substring
result = word.find('beautiful ')
print ("Substring 'beautiful ' found at index:", result )
# Substring is searched with start index 2
print(word.find('its', 2))
# Substring is searched with start index 10
print(word.find('its', 10))
# Substring is searched between start index 4 and end index 10
print(word.find('its', 4, 10))
# Substring is searched start index 10 and end index 20
print(word.find('its ', 10, 20))
# How to use find()
if (word.find('sunny') != -1):
print ("Contains given substring ")
else:
print ("Doesn't contains given substring")
Substring 'beautiful ' found at index: 12
6
-1
6
-1
Doesn't contains given substring
in
” operator checks if a substring is present within a string, returns TRUE ** if found else returns **FALSE.word = "Hello its a beautiful day"
sub1="beautiful"
sub2="sunny"
print(sub1 in word)
print(sub2 in word)
#Output
True
False
count()
method checks for the occurrence of a substring in a string; if not found, return 0.word = "Hello its a beautiful day"
sub1="beautiful"
sub2="Hello"
sub3="Sunny"
print(word.count(sub1))
print(word.count(sub2))
print(word.count(sub3))
# Output
1
1
0
word = "Hello its a beautiful day"
try :
result = word.index("beautiful")
print ("beautiful is present in the string.")
except :
print ("beautiful is not present in the string.")
# Output
beautiful is present in the string.
import operator
word = "Hello its a beautiful day"
if operator.contains(word, "beautiful"):
print ("beautiful is present in the string.")
else :
print ("beautiful is not present in the string.")
# Output
beautiful is present in the string.