Monday, July 12, 2021

String slicing


Used to access a particular part of list/tuple/string.


a=[10,20,30,40,50]

a[0:3]    # Output: 10 20 30

: is slicing operator

number or index to left of colon is included and right of colon is excluded.

When it is my_list[1:5] elements in index from 1 to 4(included) will be printed.


SYNTAX

my_list[starting_index:ending_index:step]

here step is the increment or decrement value, the default value is 1.

Starting at starting_index increment/decrement by step, to ending value will be the operation of slicing operator.

my_list=["helloworld"] 

my_list[0:5]    # output - hello

my_list[0:5:2]   
# output - hlo   (incrementing by 2)

here the 3rd parameter(step) denotes the increment/decrement.

my_list[::]  
# output - helloworld

my_list[::-1]  
# output - (reverses the entire list) dlrowolleh

 

String slicing:

my_string="HelloWorld" 

my_string=[0:5] will return string characters from 0th index to 4th index.
 
output = "Hello"

my_string=[2:8] will return string characters from 2nd index to 7th index.
 
output = "lloWor" 
 
As you may get the logic now, my_string=[2:8] starting value(2) is included and ending value(8) is ignored.
 
my_string=[2:8:3]  
Here the step is 3.
Every value whose position is multiple of 3 will be taken into account.
 
Example - 1
my_string="HelloWorld"
my_string[0:7:3] will print "Hlo"
 
my_string=[starting index:ending index:step] 
 
Example - 2
my_string[::] 
by default,
starting index will be 0
ending index will be len(my_string)-1 and 
step will be 1 
So the output will be "HelloWorld"
 
Example - 3
 
my_string[::-1] by iterates the string backwards

So the output will be "dlroWolleH"
 

Example -4

 

Single and multiple line string

string1 = "I love BTS songs"   #single line value is enclosed within double quotes.

string2 = "'I love

                 Blueming

                 Celebrity

                 Through the night

                 you and I

                 eight

                 by IU too'''  #multiple line string is enclosed with in triple quotes.

 

 

 

 

 

No comments:

Post a Comment

Anaconda Installation

In this post we will discuss about Anaconda and its installation. Anaconda comes with number of applications(jupyter notebook included), dat...