String Operations

Concatenation

Concatentation is joining strings together.

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

1
2
3
#
fullname = forename + ' ' + surname
#

String Length

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

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

Characters and ASCII (for Higher)

1
2
3
4
5
6
7
8
#
# 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:

1
2
3
4
5
6
#
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.

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