Pre-defined Functions

A pre-defined is a function already built into the programming language to perform mathematical calculation, manipulate text, format values etc.

Slicing Strings into Substrings

A string is essentially just an array of characters. Many operations and functions that work with an array also work with a string. A single character in a string is accessed by identifying its index position (in exactly the same way as an array). A sequence of characters (a substring) can also be defined by stating the range positions [start:finish]. The sample lines of code below highlight these ideas.

scots = “Whisky”

print(scots[1])                                  # ‘h’

print(scots[-2])                                 #  ‘k’

scots[2] == scots[-4]                        # True

# When first slice value is omitted, it defaults to 0

# When second value is omitted, it defaults to end

print(scots[1:4])                   #  ‘his’

print(scots[-3:])                                #  ‘sky’

irish = scots[:5] + “e” + scots[5]      # ‘Whiskey’

irish = scots[-6:] + “e” + scots[-1]    # ‘Whiskey’

Converting between ASCII Codes and Characters

Any programs that manipulate text or work with single keystroke inputs often need to work at ASCII level. The two functions described below can facilitate this.

Modulus

The modulus operator is used to retrieve the remainder after division by a number.  It is useful for identifying if a number is even or odd, doing clock arithmetic (e.g. convert seconds into hours: minutes: seconds).  The floor division operator is also listed below since it is often used together with modulus.

Data Type Casting

There are situations in programming where it is necessary to change the data type of a variable. The technical term for this is casting. For example user entries made in response to the input() function in Python are returned as strings. This is no good if they need to be manipulated as numbers in calculations. Similarly, when reading data from a text file into variables, everything (even numbers) is read as strings.