How can a program work with text?
A string stores text such as a name, password, product code or sentence.
String manipulation means examining or changing that text. Programs often need to count its characters or take out one section.
String manipulation means working with text. Two important routines are LENGTH, which counts characters, and SUBSTRING, which extracts part of a string.
A string stores text such as a name, password, product code or sentence.
String manipulation means examining or changing that text. Programs often need to count its characters or take out one section.
The string "CODE" contains four characters: C, O, D and E.
Spaces also count as characters. The string "Hello Sam" contains nine characters because the space is included.
Imagine highlighting text in a document. You can count how many characters are present, or highlight only the section you need.
LENGTH is like checking the character count. SUBSTRING is like highlighting and copying part of the text.
The program stores the word COMPUTER, finds its length and extracts the first three characters.
Word <- "COMPUTER" NumberOfCharacters <- LENGTH(Word) FirstPart <- SUBSTRING(Word, 1, 3) OUTPUT NumberOfCharacters OUTPUT FirstPart
word = "COMPUTER" number_of_characters = len(word) first_part = word[0:3] print(number_of_characters) print(first_part)
In Cambridge-style pseudocode, SUBSTRING(Text, Start, Length) means:
For example, SUBSTRING("PASSWORD", 1, 4) returns "PASS".
Students sometimes count only the visible letters and ignore spaces.
Also remember that Python normally starts character positions at zero, while Cambridge pseudocode examples usually start at one.