Python | Get substring from given string using list slicing

Code # 1:

In this example we will see how to extract a substring from the end or the beginning of a string.

# Python3 demo code
# create a substring from a string

  
# Initializing string

ini_string = ` xbzefdgstb`

 
# print start line and character

print ( "initial_strings:" , ini_string)

 
# create a substring from the beginning of the line
# define cast the length to which substring is required

sstring_strt = ini_string [: 2 ]

sstring_end = ini_string [ 3 :]

  
# print result

print ( "print resultant substring from start" , sstring_strt)

print ( "print resultant substring from end" , sstring_end)

Output :

 initial_strings: xbzefdgstb print resultant substring from start xb print resulta nt substring from end efdgstb 

Code # 2:

In this example we will see how to create a string by taking characters from a specific positional space.

# Python3 demo code
# create a substring from a string

 
# Initializing string

ini_string = `xbzefdgstb`

  
# print start line and character

print ( " initial_strings: " , ini_string)

  
# create a substring from to the power of the element
# after a certain space of the position
# determine the length to which substring is required

sstring_alt = ini_string [:: 2 ]

sstring_gap2 = ini_string [:: 3 ]

 
# print result

print ( "print resultant substring from start" , sstring_alt)

print ( "print resultant substring from end " , sstring_gap2)

Exit :

 initial_strings: xbzefdgstb print resultant substring from start xzfgt print resultant substring from end xegb  

Code # 3:

In this example, we consider both cases of taking a line from the middle with some positional break between characters.

# Python3 demo code
# create a substring from a string

 
# Initialization string

ini_string = `xbzefdgstb`

  
# print start line and character

print ( "initial_strin gs: " , ini_string)

  
# create a substring using the element
# after a certain space position
# in a certain length

sstring = ini_string [ 2 : 7 : 2 ]

 
# print result

print ( "print resultant substring" , sstring)

Output :

 initial_strings: xbzefdgstb print resultant substring zfg