Strings ======= .. contents:: :local: 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. .. interactive_code_block:: :caption: Complete the following script abbreviating a term term = 'Light Amplification by Stimulated Emission of Radiation' # Create a variable to be able to add the roman symbols abbreviated_term = '' #Iterate over the characters in the term for #.......... # If the character is uppercase... if #.......... # ...add it to the abbreviation abbreviated_term += #.......... print(abbreviated_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. .. interactive_code_block:: :caption: Common string manipulations - testing or changing the case of a string term = 'Light Amplification by Stimulated Emission of Radiation' # Getting the case of the fifth character print(term[4].islower()) print(term[4].isupper(), '\\n') # Changing the case print(term.lower()) print(term.upper(), '\\n') Go to :ref:`solution `. Exercise 2 - Reverse a string ----------------------------- Approach ^^^^^^^^ .. interactive_code_block:: :caption: Complete the script to reverse a string character by character string = 'A man, a plan, a canal - Panama!' reversed_string = #.......... print(reversed_string) 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``) .. interactive_code_block:: :caption: Different possibilities of slicing a string text = '0123456789' # Using the start argument to slice single characters print(text[0]) # 1st character --> '0' print(text[2]) # 3rd character --> '2' print(text[6]) # 7th character --> '6' print(text[-1]) # last before 1st character from the end --> '9' print(text[-2]) # last before 2nd character from the end --> '8' print(text[-6], '\\n') # last before 7th character from the end --> '4' # Using the start and stop arguments to slice a sequence of characters print(text[0:6]) # 1st up to 7th character --> '012345' print(text[:6]) # 1st up to 7th character, shorter version --> '012345' print(text[2:]) # 3rd to last character --> '23456789' print(text[2:6]) # 3rd up to 7th character --> '2345' print(text[:], '\\n') # All characters --> '0123456789' # Using the start, stop and step arguments to slice a sequence of characters print(text[:6:2]) # 1st up to 7th, every 2nd character --> '024' print(text[6::2]) # 7th to last, every 2nd character --> '68' print(text[:6:-1]) # backwards, last to 7th character --> '987' print(text[6::-1]) # backwards, 7th to 1st character --> '6543210' print(text[::-1]) # backwards, all characters --> '9876543210' .. That one is still a riddle: print(text[:-6:-1]) Go to :ref:`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. .. interactive_code_block:: Complete the script to reverse a string word by word string = 'Are you as excited as i am?' # Use a single space as a sperator separator = ' ' # Split the string to a list of words list_of_words = #.......... # Reverse that list of words #.......... # Join the list of words back together to a string using the seperator string = #.......... print(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. .. interactive_code_block:: Splitting a string to a list of strings string = 'Are you as excited as i am?' seperator = ' ' list_of_words = string.split(seperator) print(list_of_words) If the seperator is omitted, its default value ``None`` will be used, where sequences of whitespace characters are treated as single seperator. .. interactive_code_block:: Splitting a string to a list of strings string = 'Are you as excited as i am?' # Using a single space ' ' as seperator list_of_words = string.split(' ') print(list_of_words) # Using a the default value 'None' as seperator list_of_words = string.split() print(list_of_words) Reversing a list """""""""""""""" The method ``.reverse()`` of the ``list`` class can be used to reverse the sequence of its items. .. interactive_code_block:: Reversing a list list_of_words = ['Are', 'you', 'as', 'excited', 'as', 'i', 'am?'] list_of_words.reverse() print(list_of_words) 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. .. interactive_code_block:: Complete the script to reverse a string word by word list_of_words = ['Are', 'you', 'as', 'excited', 'as', 'i', 'am?'] seperator = ' ' string = seperator.join(list_of_words) print(string) Go to :ref:`solution `.