Computer Science, asked by Bhanupartap1275, 10 months ago

What is a string slice ? How is it useful ?

Answers

Answered by maryamkincsem
9

The process in which syntax is expanded to get a Substring from a simple string is known as String Slicing.

Explanation:

  • It is mostly applicable in programming languages i.e. Java, Python, etc.

  • In the case of Java, the slice method takes out the string and take the produced part in a new string.

  • In the case of Python, the sting helps the procedure of slicing to produce a substring.

Learn more about it.

How is a string slice useful in python​

https://brainly.in/question/11924821

Answered by Equestriadash
20

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

The syntax of a slice command is as follows:

string_name[start:end:step]

Note: The string value must be assigned to a variable before one can perform slicing.

The syntax is similar to the range function, mostly used in loops.

range(start, stop, step)

It's important to understand the index values of each character before one can perform slicing.

An example to demonstrate its working:

  • str1 = Python Programming

The index values, [both positive and negative respectively will be as follows:

\begin{array}{|c|c|c|} \cline{1-3} \sf Character & \sf Positive & \sf Negative\\ \cline{1-3} \sf P & 0 & -18\\ \cline{1-3} \sf y & 1 & -17\\ \cline{1-3} \sf t & 2 & -16\\ \cline{1-3}  \sf h & 3 & -15\\ \cline{1-3}  \sf o & 4 & -14\\ \cline{1-3} \sf n & 5 & -13\\ \cline{1-3} & 6 & -12\\ \cline{1-3} \end{array}

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

Note that special characters like spacing, symbols, etc also have index values.

Now, suppose this was our slice command:

>>> str1[0:17]

Output:

'Python Programmin'

The reason the last character wasn't printed, is similar to how the range function doesn't display the last character either. In order to do so, you'll need to add a number to it again.

>>> str1[0:18]

'Python Programming'

Since we've given the start value as 0 and the ending value as 18, it'll print all the characters, starting from the character of index 0.

Now let's try an example with negative numbers.

>>> str1[2:-1]

'thon Programmin'

The starting index value given was 2, and the ending index value given was -1 which is equivalent to 'g'. Again, as mentioned earlier, the last value will not be displayed.

Now, an example with step values.

>>> str1[0:18:2]

'Pto rgamn'

Here, it has skipped each character by 2 values, as 2 is given as the step value.

Similar questions
Math, 1 year ago