Python inbuilt String Functions

index()

The index() method finds the first occurrence of the specified value.
The index() method returns error if the value is not found.

Syntax
string.index(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.index("apple")
print(x)

#search from 10 position
n = "I love apples, apple are my favorite fruit. apples are red"
x = txt.index("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.index("apple",18,len(n))
print(x)

#In below code 
# error will get displayed as string is not present

#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.index("apple",48,len(n))
#print(x)
#Output

7
15
43

endswith()

The endswith() method returns True if the string ends with the specified value, otherwise False.

Syntax
string.endswith(value, start, end)

value : The value to check if the string ends with (Required)
start : An Integer specifying at which position to start the search (Optional)
end : An Integer specifying at which position to end the search(Optional)

n="Hello How are you"
print(n.endswith('you'))

n="Hello How are you"
print(n.endswith('you',1,10))
#Output

True
False

expandtabs()

The expandtabsize() method sets the tab size to the specified number of whitespaces.

Syntax
string.exandtabs(tabsize)

tabsize : A number specifying the tabsize. Default tabsize is 8 (Optional)

txt = "H\te\tl\tl\to"
x =  txt.expandtabs(2)
print(x)

txt = "H\te\tl\tl\to"
x =  txt.expandtabs(5)
print(x)

txt = "H\te\tl\tl\to"
x =  txt.expandtabs(10)
print(x)
#Output

H e l l o
H    e    l    l    o
H         e         l         l         o

Python String inbuilt Methods       Python Math inbuilt Methods       Python Date And Time inbuilt Methods      Python Random inbuilt Methods