Strings
Handling strings with functions
Write a function that builds a new string.
Since strings cannot be changed, functions that work on strings usually build a new string and return it. The book's examples:
- charCount(ch, st) (Program 8-1) traverses st and counts the characters equal to ch. In 'Today is a Holiday', 'a' occurs 3 times.
- replaceVowel(st) (Program 8-2) builds a new string: for each character of st, it adds a star symbol if the character is a vowel, and the character itself otherwise.
- Program 8-3 prints a string backwards, using negative indices from -1 down to -len(st). It only prints; it does not make a new string.
- reverseString(st) (Program 8-4) builds the reversed string in a new variable, newstr, and returns it.
- checkPalin(st) (Program 8-5) checks whether a string is a palindrome (reads the same both ways). It compares the first character with the last, the second with the second-last, and so on, moving inwards. 'level' is a palindrome; 'python' is not.
The pattern to remember: start with an empty string, newstr = '', traverse the original, and add characters to newstr one by one (newstr = newstr + ch). At the end, return newstr.
Strings are immutable, so build a new one.
Practise this lesson
Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.
No account, no email address. Opens the real product.