String Slicing and Operations on Strings
names = "Sindhu , Shilpa"
print(names[0:6]) #output = Sindhu
#print(names[1st index:(n-1)th index]) where (n-1)=5
'''
In Programming, counting always starts with 0.
Length of a String:
We can find the length of a string using len() function.
'''
print(len(names))#output = 15
fruit = "Orange"
len1 = len(fruit)
print("Orange is a" ,len1, "letter word.")
#output = Orange is a 6 letter word.
'''For functions, we use parenthesis and for string slicing, we use square brackets.'''
alphabets = "ABCDE"
alphabetslen = len(alphabets)
print(alphabetslen) #output = 5
print(alphabets[0:4]) #output = ABCD
print(alphabets[ :4]) #output = ABCD
# In case, we do not put any index at the place of 1st index, Python considers it as 0 by default.
print(alphabets[1:4]) #output = BCD
#print(alphabets[1st index:3rd index]) i.e. including 1 but not 4
print(alphabets[:]) #output = ABCDE
#In case we do not mention any index within the square brackets, Pythons considers it as [0:5] i.e. [0:(n-1)] where n=no of last character when counting starts from 1
print(alphabets[0:-3]) #output = AB
#In this case, Python interprets it as print(alphabets[0:len(alphabets)-3]) i.e. there will be a deduction of -3 from the len(alphabets) i.e. [0:2]
print(alphabets[-1:-3]) #output =
# Here, Python interprets it as print(alphabets[4:2]) (no sense)
print(alphabets[-3:-1]) #output = CD
Comments
Post a Comment