Computer Science, asked by rlmlatha, 5 months ago

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 Equestriadash
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:

\begin{array}{|c|c|c|}\cline{1-3}\bf Character&\bf Positive& \bf Negative\\\cline{1-3}\sf P&0&-17\\\cline{1-3}\sf o&1&-16\\\cline{1-3}\sf l&2&-15\\\cline{1-3}\sf i&3&-14\\\cline{1-3}\sf t&4&-13\\\cline{1-3}\sf i&5&-12\\\cline{1-3}\sf c&6&-11\\\cline{1-3}\sf a &7&-10\\\cline{1-3}\sf l &8&-9\\\cline{1-3} &9&-8\\\cline{1-3}\sf S &10&-7\\\cline{1-3}\sf c &11&-6\\\cline{1-3}\sf i &12&-5\\\cline{1-3}\sf e &13&-4\\\cline{1-3}\sf n &14&-3\\\cline{1-3}\sf c &15&-2\\\cline{1-3}\sf e & 16 & -1\\\cline{1-3}\end{array}

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