Chapter 7: Stringing Characters Together

The answers on this page show ONE way to solve the exercises. However, there are usually OTHER ways to accomplish the same thing. This is OK!

A suggested solution is ONE way to solve the problem, not the ONLY way.

Chapter Sandbox

Use the editor below to test out any of the solutions!

Solutions

Part One: Bracket Notation

  1. Identify the result for each of the following statements:

    1. 'Characters'[8] = r

    1. len("Do spaces count?") = 16

    There’s no starter code for this one, just try it on your own with old-fashioned pencil and paper!

  2. Use bracket notation to:

    1. Print a slice of the first 12 characters from "Strings_are_sequences_of_characters."

    1
    2
    text = 'Strings_are_sequences_of_characters.'
    print(text[:12])
    
    1. Print a slice of the middle 12 characters from the same string.

    1
    2
    #simple solution that solves for just text = 'Strings_are_sequences_of_characters.'
    print(text[12:24])
    
  3. Use index values to loop backwards through a string:

    1. First, print one letter per line.

    1
    2
    3
    max_index = len(word) - 1
    for index in range(max_index, -1, -1):
    print(word[index])
    
    1. Next, instead of one letter per line, use the accumulator pattern to build up and print the reversed string. For example, if given the string 'good', your program prints doog.

    1
    2
    3
    4
    5
    6
    word = "tomato"
    new_word = ""
    for index in range(max_index, -1, -1):
        new_word += word[index]
    
    print (new_word)
    
    1. Finally, use concatenation to print the combination of the original and reversed string. For example, given the string 'tomato', your program prints tomatootamot. (If you want to be fancy, include the | character to make the output look almost like a mirrored image: tomato | otamot).

    1
    print(word + new_word)
    

Back to the exercises.

Part Two: String Methods and Operations

  1. The len() function returns the number of characters in a string. However, the function will NOT give us the length of an integer. If num = 1001, then len(num) throws an error instead of returning 4.

    1. Use str() to change num from an int to a string data type.

    2. Print the length (number of digits) in num.

    1
    2
    3
    4
    num = 1001
    
    # Exercise 1a and 1b
    print(len(str(num)))
    
    1. Modify your code to print the number of digits in a float value (e.g. num = 123.45 has 5 digits but a length of 6). The digit count should NOT include the decimal point.

    1
    2
    3
    num = 123.45
    new_num = str(num).replace(".","")
    print(len(new_num))
    
    1. What if num could be EITHER an integer or a decimal? Add an if/else statement so your code can handle both cases. (Hint: Consider using the find() method or the in operator to check if num contains a decimal point).

    1
    2
    3
    4
    5
    # Experiment! There are many ways to do this.
    if  type(num) is float or type(num) is int:
        print(len(str(num)) - str(num).count("."))
    else:
        print(len(num))
    
  2. Given word = 'bag':

    1. Set up a loop to iterate through the string of lowercase vowels, 'aeiou'.

    2. Inside the loop, create a new string from word, but with a different vowel. Use the replace() string method.

    3. Print the new string.

    1
    2
    3
    4
    5
    6
    word = 'bag'
    
    vowels = "aeiou"
    for vowel in vowels:
        new_word = word.replace("a", vowel)
        print(new_word)
    
  3. Consider a string that represents a strand of DNA: dna = " TCG-TAC-gaC-TAC-CGT-CAG-ACT-TAa-CcA-GTC-cAt-AGA-GCT    ". There are some typos in the string that you need to fix:

    1. Use the strip() method to remove the leading and trailing whitespace, and then print the result.

    1
    print(dna.strip())
    
    1. Note that you need to reassign the changes back to the dna variable in order to see them printed. Apply these fixes to your code so that print(dna) prints the DNA strand in UPPERCASE with no whitespace.

    1
    2
    dna = dna.strip().upper()
    print(dna)
    
  4. Let’s use string methods to do more work on the same DNA strand:

    1. Look for the sequence 'CAT' with find(). If found print, 'CAT found', otherwise print, 'CAT NOT found'.

    1
    2
    3
    4
    if dna.find("CAT") > -1:
        print("CAT gene found")
    else:
        print("Cat gene NOT found")
    
    1. Use count() to find the number of hyphens (-) in the string, then print the number of genes (in this case, a gene is a set of 3 letters) in the DNA strand. Note that the number of genes will be 1 more than the number of hyphens.

    1
    print(dna.count("-")+1)
    

Back to the exercises.

Part Three: String Formatting

  1. Assign your favorite, school-appropriate number and word to two variables.

    1. Use format() and index values to print the string, "Here is my number: ___, and here is my word: ___, and here is my number again: ___."

    1
    2
    3
    4
    5
    my_num = 42
    my_word = 'feckless'
    
    output = "Here is my number: {0}, and here is my word: {1}, and here is my number again: {0}."
    print(output.format(my_num, my_word)
    
  2. The following code sample works, but it can be improved.

    1
    2
    3
    4
    5
    advice = "Don't Panic"
    
    output = "The text, '{0}' contains {1} characters."
    
    print(output.format("Don't Panic", 11))
    
    1. Assuming that advice remains a string, when will the code produce the wrong output?

    When we change advice to something else.
    
    1. Why will the code do this?

    Because the print statement is hard coded with 'Don't Panic' instead of the variable name advice.
    
    1. What should the programmer do to fix the code?

    1
    2
    #One way to code the above answer:
    print(output.format(advice, len(advice)))
    

Back to the exercises.