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¶
Identify the result for each of the following statements:
'Characters'[8]
= r
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!
Use bracket notation to:
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])
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])
Use index values to loop backwards through a string:
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])
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 printsdoog
.
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)
Finally, use concatenation to print the combination of the original and reversed string. For example, given the string
'tomato'
, your program printstomatootamot
. (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)
Part Two: String Methods and Operations¶
The
len()
function returns the number of characters in a string. However, the function will NOT give us the length of an integer. Ifnum = 1001
, thenlen(num)
throws an error instead of returning4
.Use
str()
to changenum
from anint
to a string data type.Print the length (number of digits) in
num
.
1 2 3 4
num = 1001 # Exercise 1a and 1b print(len(str(num)))
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))
What if
num
could be EITHER an integer or a decimal? Add anif/else
statement so your code can handle both cases. (Hint: Consider using thefind()
method or thein
operator to check ifnum
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))
Given
word = 'bag'
:Set up a loop to iterate through the string of lowercase vowels,
'aeiou'
.Inside the loop, create a new string from
word
, but with a different vowel. Use thereplace()
string method.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)
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:Use the
strip()
method to remove the leading and trailing whitespace, and then print the result.
1
print(dna.strip())
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 thatprint(dna)
prints the DNA strand in UPPERCASE with no whitespace.
1 2
dna = dna.strip().upper() print(dna)
Let’s use string methods to do more work on the same DNA strand:
Look for the sequence
'CAT'
withfind()
. 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")
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)
Part Three: String Formatting¶
Assign your favorite, school-appropriate number and word to two variables.
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)
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))
Assuming that
advice
remains a string, when will the code produce the wrong output?
When we change advice to something else.
Why will the code do this?
Because the print statement is hard coded with 'Don't Panic' instead of the variable name advice.
What should the programmer do to fix the code?
1 2
#One way to code the above answer: print(output.format(advice, len(advice)))