slicing string in python code example

Example 1: python slice string

name = "dx4iot"
print(name[0:]) #output: dx4iot
print(name[0:3]) #output: dx4
#==== reverse a string ====#
print(name[::-1]) #output: toi4xd
print(name[0:6:2]) #output: d4o
print(name[-4:-1]) #output: 4io

Example 2: get a slice of string in python

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

Example 3: python string slicing

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

Example 4: string slicing in python 3 arguments

#[start:end:step]
>>> range(10)[::2]
[0, 2, 4, 6, 8]

Example 5: Python - Slicing Strings

b = "Hello, World!"
print(b[2:5])