Invoker
0
Q:

how to slice a string in python

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
a = 'hello'
print(a[1:2])
1
string = "something"

slice = string[0:3] # will be "som"
slice = string[0:-3] # will be "someth"
slice = string[3:] # will be "thing"
slice = string[:3] # same as first slice
slice = string[::2] # will be "smtig" -- it goes 2 step each time
0

New to Communities?

Join the community