Foundations of Python

You are currently auditing this course.
90 / 134

String Slices

A segment of a string is called a slice.

s = "cloudxlab"
print(s[1:5])

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,

    print(s[4:4])
    

    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,

print(s[-1])

For second last character,

print(s[-2])

and likewise.

INSTRUCTIONS
  • 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


Loading comments...