Higher – Substring Operations

pre-defined functions (with parameters):

  • to create substrings

In Python we can treat strings as arrays of characters. We do this by using

string[start:stop:step]

where

  • start is the postion of the first character to be displayed.
  • stop is the postion to stop displaying characters (not displayed).
  • step is the step value, just like a for loop.

So there is no need to use a function to slice a string.

We can dispay any character by using

string[position] – where position is the index in the string (remember index starts at zero)

We can display the left most portion of a string by using

string[:stop] – this means display all the character to the stop postion. So “0123456789”[:6] would display the first 6 characters ‘012345’

We can display the right most portion of a string by using

string[-stop:] – this displays all the characters from the end to the stop postion. So “0123456789”[-6:] would display the last 6 characters ‘456789’

We can display characters in the middle of a string by using

string[start:stop] – displays the characters from start to stop (not displayed) . So “0123456789”[2:5] would display the third (remember positions start at 0) to fifth characters ‘234’

We can simplify the process by creating functions to slice the strings. In the example below I have called them left, right and mid which mirror how the Excel functions work.


def left(string,X):
   # This function returns the left most X characters of the given string
   return string[:X]

def right(string,X):
   # This function returns the right most X characters of the given string
   return string[-X:]

def mid(string,position,size):
   # This function returns a substring of given size from string, starting from the position given
   return string[position-1:position-1+size]

def main():
   string="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
   print(left(string,6)) # print the first 6 characters of the string
   print(right(string,10)) # print the last 6 characters of the string
   print(mid(string,13,5)) # print the 5 characters from the 13 character

main()

Further information can be found at:-

  • https://www.w3schools.com/python/python_strings.asp
  • https://realpython.com/python-strings/

Leave a Reply

Your email address will not be published. Required fields are marked *