count()
The count() method returns the number of times a specified value appears in the string.
Syntax
string.count(value, start, end)
value : A String. The string to value to search for (Required)
start : An Integer. The position to start the search. Default is 0 (Optional)
end : An Integer. The position to end the search. Default is the end of the string(Optional).
n = “I love apples, apple are my favourite fruit”
x = n.count(“apple”)
print(x)
Return the number of times the value “apple” appears in the string
txt = "I love apples, apple are my favorite fruit apples are red" x = txt.count("apple") print(x) #search from 10 position n = "I love apples, apple are my favorite fruit. apples are red" x = txt.count("apple",10) print(x) #search from 10 position n = "I love apples, apple are my favorite fruit apples are red" x = txt.count("apple",10,24) print(x)
#Output 3 2 1
len()
This function helps us to find the length of the string. that is the total number of characters in the string.
Spaces are included in the length
Syntax:
print(len(string))
Gives the length of the string
n="hello" print(len(n)) n="hello world" n1=len(n) print("length = ",n1) n="Hello How are you" n1=len(n) print("length = ",n1)
#Output 5 length = 11 length = 17
find()
The find() method finds the first occurrence of the specified value.
The find() method returns -1 if the value is not found.
The find() method is almost the same as the index() method, the only difference is that the index() method raises an exception if the value is not found.
Syntax
string.find(value, start, end)
value: Required. The value to search for
start: Optional. Where to start the search. Default is 0
end: Optional. Where to end the search. Default is to the end of the string
txt = "I love apples, apple are my favorite fruit apples are red" x = txt.find("apple") print(x) #search from 10 position n = "I love apples, apple are my favorite fruit. apples are red" x = txt.find("apple",10) print(x) #search from 18 position to len of the string n = "I love apples, apple are my favorite fruit apples are red" #print(len(n)) x = txt.find("apple",18,len(n)) print(x) #search from 48 position to len of the string n = "I love apples, apple are my favorite fruit apples are red" #print(len(n)) x = txt.find("apple",48,len(n)) print(x)
#Output 7 15 43 -1
Python String inbuilt Methods Python Math inbuilt Methods Python Date And Time inbuilt Methods Python Random inbuilt Methods