The use of basic string manipulation: slicing
2.2.3 Additional Programming Techniques
Practise exam questionsAdditional Programming Techniques — Note 2 of 12
e.g. stringname.subString(startingPosition, numberOfCharacters)
String slicing extracts a portion (substring) of a string based on position indices. Strings are zero-indexed, meaning the first character is at position 0. You can also find the length of a string, convert it to uppercase or lowercase, and extract characters from the left or right.
.length gives the number of characters in a string. E.g. "Monday".length = 6..substring(start, count) extracts 'count' characters starting from 'start' position..left(n) returns the first n characters; .right(n) returns the last n characters..upper converts a string to UPPERCASE. E.g. "abcd1234".upper = "ABCD1234"..lower converts a string to lowercase.ASC() returns the ASCII code of a character; CHR() returns the character for a given code.+, e.g. pilotCode = a + b + str(c)..length → len(text); .left(n) → text[:n]; .right(n) → text[-n:]; .substring(start, count) → text[start:start + count]; .upper / .lower → .upper() / .lower(); ASC() / CHR() → ord() / chr().text[x:y] the character at position y is NOT included: "Python"[0:3] gives "Pyt" (positions 0, 1 and 2).The process of performing operations on strings, such as concatenation, slicing, measuring length or changing case.
+ for concatenation. Commas in print() separate items, they DON'T join strings. Use + to concatenate.staffID = surname + str(year), then while staffID.length < 10: staffID = staffID + "x" pads it to length 10.str() converts a number to a string for concatenation: str(900) gives "900".message = "abcd1234" → message.left(4) = "abcd", message.right(4) = "1234", int(message.right(4)) * 2 = 2468.word = "ComputerScience"
print(len(word)) # 15 (length)
print(word[0:4]) # "Comp" (first 4 chars)
print(word[3:8]) # "puter" (index 3 to 7)
print(word[-3:]) # "nce" (last 3 chars)
print(word.upper()) # "COMPUTERSCIENCE"
print(word.lower()) # "computerscience"
print(ord("A")) # 65 (ASCII code)
print(chr(97)) # 'a' (character from code)text = "Hello"
print(len(text)) # 5 length
print("Python"[0:3]) # Pyt substring [start:end], end not included
print(text[:3]) # Hel left 3 characters
print(text[-2:]) # lo right 2 characters
print("Hi " + "there") # Hi there concatenation
print("hello".upper()) # HELLO uppercase
print("HELLO".lower()) # hello lowercase
print(ord("A")) # 65 ASCII code of a character
print(chr(65)) # A character for an ASCII codeReady to test yourself?
Practise 2.2.3 questions