Tags
Asked 3 years ago
2 Aug 2021
Views 420
Patricia

Patricia posted

example of slicing in Python ?

What is slicing ? give example of it in Python
steave

steave
answered Aug 4 '21 00:00

slicing stands for remove some part of values and show some of them
for slicing , you can use :n operator where n is integer positive or negative value
a:n means it shows value of a from 0 to n .


a = [1,2,3,4,5,6]
for t in a[:2]:
	print(t)


a = [1,2,3,4,5,6]
a[:2] means it shows values of a from 0 to 2 , so it will print

1
2


for slicing, n: means it will slice from n to the end of the values(total length of values)
so suppose in above example , a[2:] means it will start 2 index to total length of a which is end of the list


a = [1,2,3,4,5,6]
print(a[2:])


it will print

a = [1,2,3,4,5,6]
for t in a[:2]:
	print(t)
8
jagdish

jagdish
answered Aug 4 '21 00:00

string slicing in python

for example

a = 'abcdefjkl'
print(a) 


if we write same in slicing matter print(a) is equal to print(a[0:]) or print(a[0:9])


a = 'abcdefjkl'
print(a[:2]) 


it will print ab because a[:2] means a[0:2] so it will ab
if a[2:] is like a[2:9] which means it start with skipping two first character and show print remaining like cdefjkl

Post Answer