Multiple ways to get Substring of a string in Python|Slicing example

This tutorial explains finding the substring(slice) of a given string.

For example

The string contains hello, substring possible values h, e,l,l,0 or hello, etc.

Substring or slicing is a part of a main string with a given index.

Let’s understand how string is stored with an index

                    +---+---+---+---+---+---+
                    | h | e | l | l | o | w |
                    +---+---+---+---+---+---+
Start (Positive):     0   1   2   3   4   5   
End (positive) :      5   4   3   2   1   0

String slice in Python example

  • one way using string[start:end] Substring calcuate using string[start:end] syntax.
string[start:end]

start and end are starting and ending index and returns the characters of given indexes. Returns a string with start and end-1 index.

if values are positive, the Starting and index are iterable in the forward direction. For example, a string contains hello, start=0 is the h character, end=4 (length-1) is o.

if values are negative, the Starting and index are iterable in the reverse direction. For example, string contains hello, start=-1 is 0 character, end=-4 (-length-1) is h.

Here is an example

str="hello welcome"

print(str[1:]) # ello welcome
print(str[:1]) # h
print(str[-1:]) # e
print(str[:-1]) # hello welcom
print(str[1:-1]) # ello welcom
print(str[:]) # hello welcome

str[1:]: start index is 1, end index is unknown means, end of a string. str[:1]: start is unknown means the beginning of a string and end is 1. str[-1:]:, start index is the second character from the end of a string, end is begging in reverse direction str[:-1]: start is unknown, end=-1 ie second character from end of a string str[1:-1]: start is 2 character from the beginning, end=-1 second character from end. str[:]: returns a complete string.

  • Second way using string[start:end:step]

Another syntax we can use with step value

string[start:end:step]
  • start: start index of a string, includes the character in the substring, default is 0.
  • end: End index of a string, does not include the character in a substring. The default is length -1
  • step: Amount of index increases, default is 1, for negative, substring iterable in reverse direction

Here is an example

str="hello welcome"

print(str[1::])# ello welcome
print(str[::1])# hello welcome
print(str[1:2:4]) # e
print(str[-1:None:None]) #e
print(str[1:None:-1]) #eh
print(str[:-1:None]) # hello welcom