Consider the following string mySubject :
mySubject = “Political Science”
What will be the output of the following string operations :
i. print (mySubject [ 0:len (mySubject) ] )
i. print (mySubject [ - 7 : -1 ] )
i. print (mySubject [ : : 2 ] )
i. print (mySubject [ : 3 ] + mySubject [ 3 : ] )
i. print (mySubject [ : : - 2 ] )
Answers
Answered by
85
We have mySubject = "Political Science".
Let's first understand and identify what the index values of each character are.
String slicing is the act of retrieving a substring from a given string using index values.
- Positive indexing starts from 0 and traverses through the string from left to right.
- Negative indexing starts from -1 and traverses through the string from right to left.
Here are the positive and negative index values of the given string:
i. print(mySubject[0:len(mySubject) ])
len() calculates the number of characters in the variable. Since len(mySubject) is 17, and the starting value is 0, all the characters will be printed.
- Political Science
ii. print(mySubject[-7:-1 ])
- Scienc
iii. print(mySubject[::2])
- PltclSine
iv. print(mySubject[:3] + mySubject [3 :])
- Political Science
v. print(mySubject[::-2])
- eniSlctlP
A string slice follows a similar syntax:
string_name[start:stop:step]
- start - indicates the character it should start from
- stop - indicates the character is should end at
- step - indicates the number of characters it should skip while traversing
NOTE:
- When no value is given as the start value, by default, it starts from 0.
- When no value is given as the stop value, by default, it starts from -1.
- When a negative value is given as the step value, the output comes in the reverse order.
Similar questions