Strings
Introduction
The str data type is one of the three built-in sequence data types (the other two are tuple and list list). Like any sequence data type it can be sliced (= single items or a sequence of items can be accessed). There are also several methods unique to the str class, e.g. methods to evaluate if a string is upper- or lowercase or also to change its case.
Exercise 1 - Abbreviate a term
Abbreviating a term within this exercise means to create a new string that consists only of the uppercase letters.
Approach
Iterate over the characters of the string and create a new string containing only the uppercase characters.
Complete the following script abbreviating a term
Know how
Testing or changing the case of a string
The methods .islower() and .isupper() of the str class can be used to test if a string is upper- or lowercase, while .lower() and .upper() can be used to change its case.
Common string manipulations - testing or changing the case of a string
Go to solution.
Exercise 2 - Reverse a string
Approach
Complete the script to reverse a string character by character
Know how
Slicing a string
Since the string and the tuple data types are immutable (= they cannot be modified) their classes have no .reverse() method like the list data type. The workaround is to slice the whole string backwards.
The slicing notation uses square brackets with up to three arguments separated by colons [start:stop:step]:
start the index of the first item (optional, defaults to
None)end the index after the last item (optional, defaults to
None)step the size of the steps (optional, defaults to
1)
Different possibilities of slicing a string
Go to solution.
Exercise 3 - Reverse a string word by word
Approach
Split the string to a list of strings by using the spaces as separators. Reverse that list and join it back to a string.
Know how
Splitting a string to a list of strings
The method .split() of the str class can be used to split a string to a list of strings by the use of a seperator.
If the seperator is omitted, its default value None will be used, where sequences of whitespace characters are treated as single seperator.
Reversing a list
The method .reverse() of the list class can be used to reverse the sequence of its items.
Joining a list of strings to a single string
The method .join() of the str class can be used join a list with the use of a seperator.
Go to solution.