Foundations of Python

90 / 134

String Slices

A segment of a string is called a slice.

s = "cloudxlab"

It prints the segment starting from the character with index 1 to index 4 i.e., 'loud'. Therefore, it includes the 1st i.e. 1 and excludes the last i.e. 5.

  • If we don't mention the 1st index before the colon, it considers the segment starting from the beginning of the string
  • If we don't mention the 2nd index after the colon, it considers the segment to the end of the string
  • If the 1st index is greater or equal to the 2nd index, it returns an empty string enclosed in the quotation,


    It prints ''. This is also a string with length 0.

We can also use negative indices to get some character from the string. Negative indices count backward from the last. To access the last character we can write,


For second last character,


and likewise.

  • Define a function with the name slicing_func that takes an argument (assume string)
  • It should print the result after slicing the string without mentioning both the 1st and 2nd elements.

Sample Input:
slicing_func("Hello World")

Sample Output:
llo World

Note - Having trouble with the assessment engine? Follow the steps listed here

Loading comments...