Strings - Solutions =================== .. contents:: :local: .. _pwp-str-ex1: Exercise 1 ---------- Solution ^^^^^^^^ .. interactive_code_block:: :caption: A 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 character in term: # If the character is uppercase... if character.isupper(): # ...add it to the abbreviation abbreviated_term += character print(abbreviated_term) Shorter solution using a list comprehension ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Simple ``for ... in ...:`` loops can sometimes be replaced by `list comprehensions `__. .. interactive_code_block:: :caption: A script abbreviating a term term = 'Light Amplification by Stimulated Emission of Radiation' # Iterate over the characters in the term using a list comprehension abbreviated_term = ''.join([character for character in term if character.isupper()]) print(abbreviated_term) .. _pwp-str-ex2: Exercise 2 ---------- Solution ^^^^^^^^ .. interactive_code_block:: :caption: A script to reverse a string character by character string = 'A man, a plan, a canal - Panama!' reversed_string = string[::-1] print(reversed_string) .. _pwp-str-ex3: Exercise 3 ---------- Solution ^^^^^^^^ .. interactive_code_block:: A 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 = string.split(separator) # Reverse that list of words list_of_words.reverse() # Join the list of words back together to a string using the seperator string = separator.join(list_of_words) print(string) .. CANNOT BE CONDENSED Condensed solution using less variables ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. interactive_code_block:: A script to reverse a string word by word string = 'Are you as excited as i am?' # The same script as before in only two lines list_of_words = string.split() string = ' '.join(list_of_words.reverse()) print(string)