Friday, October 30, 2020

,

Example program for slicing in python - python __slice__

  •  slice() function in python is used to sliced a given sequence or given object 
  • There are three parameters the first one is an starting point which is optional.
  • second parameter for slice function tells about the ending point.
  • Third one will tell the increment between each index.
Syntax:- 
slice(start, stop, step)
  • Create a slice object for slicing

result1 = slice(3)
print(result1)

)
result2 = slice(1, 5, 2)
print(slice(1, 5, 2))
slicing program in python
Example program for slicing


Program for slicing sub-string

py_string = 'Python'

slice_object = slice(3) 
print(py_string[slice_object])  # Pyt

slice_object = slice(1, 6, 2)
print(py_string[slice_object])   # yhn


  • Example program for negative slicing in python

py_str = 'Python'


slice_object = slice(-1, -4, -1)

print(py_str[slice_object])   # noh

In this program we use negative value for slicing the object
  • Example program for sublist and sub-tuple

py_l = ['P', 'y', 't', 'h', 'o', 'n']
py_t = ('P', 'y', 't', 'h', 'o', 'n')


slice_object = slice(3)
print(py_l[slice_obj]) # ['P', 'y', 't']

slice_object = slice(1, 5, 2)
print(py_t[slice_object]) # ('y', 'h')    

0 comments:

Post a Comment