Computer Science, asked by sashish8200, 20 days ago

Look at the sequence and determine the output >>> str="Python" >>> str[:-1] A. 'nohtyP' B. 'nhy' C. 'nhyP' D. 'Pytho'​

Answers

Answered by Anonymous
10

String Slices

String Slicing in Python refers to the act of extracting a substring from a given string.

GIVEN PROGRAM:

>>> str = "Python"

>>> str[:-1]

OUTPUT:

\texttt{'Pytho'}

It selects all characters of the sequence but the last. It gets all the characters from the string but the last character. \texttt{:} represents going through the string \texttt{-1} implies the last character of the string.

The syntax of string slicing is given below:

>>> \texttt{string-object[start : stop : steps]}\\

Let's take an example to understand better.

\begin{array}{l}\:0\:\:\:1\:\:\:2\:\:\:3\:\:\:4\:\:\:5\;\;\longrightarrow{\textsf{Positive indexing}}\\ \boxed{\tt P}\boxed{\tt Y}\boxed{\tt T}\boxed{\tt H}\boxed{\tt O}\boxed{\tt N}\\\text{-6}\:\text{-5}\: \text{-4}\:\:\text{-3}\:\text{-2}\:\:\text{-1}\;\;\longrightarrow{ \textsf{Negative indexing}}\end{array}

str[1:5]

  • str[1:5] is 'YTHO' - characters starting at index 1 and extending up to but not including index 5.

str[1:4]

  • str[1:5] is 'YTH' - characters starting at index 1 and extending up to but not including index 4.

str[1:3]

  • str[1:5] is 'YT' - characters starting at index 1 and extending up to but not including index 3.

str[1:2]

  • str[1:5] is 'Y' - characters starting at index 1 and extending up to but not including index 2.

str[:-1]

  • str[:-1] is 'PYTHO' - omitting either index defaults to the start or end of the string.

str[:]

  • str[:] is 'PYTHON' - omitting both always give us the copy of whole string.
Similar questions