Q:

python string slicing

str = 'codegrepper'
# str[start:end:step]
#by default: start = 0, end = len(str), step = 1
print(str[:]) 		#codegrepper
print(str[::]) 		#codegrepper
print(str[5:]) 		#repper
print(str[:8]) 		#codegrep
print(str[::2]) 	#cdgepr
print(str[2:8]) 	#degrep
print(str[2:8:2]) 	#dge
#step < 0 : reverse
print(str[::-1]) 	#reppergedoc
print(str[::-3]) 	#rpgo
# str[start:end:-1]	means start from the end, go backward and stop at start
print(str[8:3:-1]) 	#pperg
4
my_string = "Hey, This is a sample text"
print(my_string[2:]) #prints y, This is a sample text
print(my_string[2:7]) #prints y, Th excluding the last index
print(my_string[2::2]) #prints y hsi  apetx
print(my_string[::-1]) #reverses the string => txet elpmas a si sihT ,yeH
6
#[start:end:step]
>>> range(10)[::2]
[0, 2, 4, 6, 8]
3
a = 'hello'
print(a[1:2])
1

New to Communities?

Join the community