String Operations

Concatenation

Concatentation is joining strings together.

The SQA will use ampersand (&), but Python uses plus (+) signs.

#
fullname = forename + ' ' + surname
#

String Length

The len() function will return the number of characters in a string.

#
pin = input("Enter your PIN:")
pinLength = len(pin)
print(f"That has {pinLength} characters")
#

Characters and ASCII (for Higher)

#
# ord - returns the number representing the unicode code of a specified 
number = ord("A")

# chr - returns the character that represents the specified
letter = chr(65) 
 
#

String Slicing (Substrings) (for Higher)

Each character in a string has an index number, starting at zero.

index     0 1 2 3 4 5 6 7 8
string    A n d e r s o n !

Picking any single character:

#
firstLetter = string[0]
secondLetter = string[1]
#
lastLetter = string[-1]
#

Picking several characters:

Give the index of the start letter, and the index of ending letter plus one.

#
letters2and3 = string[2:4]
letters4to7 = string[4:8]
#