10.6. Solutions to Chapter 8 Exercises#

10.6.1. Exercise 1#

What would be the output of the following code?

'{age:d}, {name}, {name}'.format(age=28, name='John')
'{age:d}, {name}, {name}'.format(age=28, name='John')
'28, John, John'

10.6.2. Exercise 2#

What would the following code display?

'{0:d}, {1}, {1}'.format(28, 'John')
'{0:d}, {1}, {1}'.format(28, 'John')
'28, John, John'

Starting from left to right, just like in indexing, the arguments are given implicitly indices. In this case, 0 corresponds to 28 and 1 to John.

10.6.3. Exercise 3#

Create the following string and print it:

------------------------
Welcome to Food Science!
------------------------
upper_part = '-'*25
text = 'Welcome to Food Science!'
bottom_part = '-'*25
banner = '\n'.join([upper_part, text, bottom_part])
print(banner)
-------------------------
Welcome to Food Science!
-------------------------

10.6.4. Exercise 4#

What will be the output of the following statements:

  • 'apple'.replace('pp', 'nk')

  • 'orange'[3:]

  • 'pear'.replace('p', 'b').title()

print('apple'.replace('pp', 'nk'))
print('orange'[3:])
print('pear'.replace('p', 'b').title())
ankle
nge
Bear

10.6.5. Exercise 5#

What will be the output of the following statements:

  • 'elc ' in 'Welcome to Food Science!'

  • 'welcome' in 'Welcome to Food Science!'

print('elc ' in 'Welcome to Food Science!')
print('welcome' in 'Welcome to Food Science!')
False
False

elc contains a space after c, that is why that substring is not part of the string. While, in the case of welcome, it starts with a lowercase letter.

10.6.6. Exercise 6#

Given the text below, build a dictionary to map a word to the number of times it appears in the text. Then print only the characters that appear more than once. Also remove any empty character. You have to use the splitline() method. NOTE: This is the same exercise as Exercise 6 in Sets and Dictionaries but here you are required to use splitline() to solve it.

text = """To be, or not to be, that is the question: 
Whether tis nobler in the mind to suffer 
The slings and arrows of outrageous fortune,
Or to take Arms against a Sea of troubles,
And by opposing end them: to die, to sleep
No more; and by a sleep, to say we end."""
list_of_lines = text.splitlines()
list_of_words = []
dict_of_words = {}

for line in list_of_lines:
    for word in line.split():
        if word!='':
            list_of_words.append(word)

set_of_words = set(list_of_words)
for word in set_of_words:
    dict_of_words[word] = list_of_words.count(word)

print(*((word, counter) for word, counter in dict_of_words.items() if counter > 1))
('and', 2) ('the', 2) ('of', 2) ('by', 2) ('be,', 2) ('to', 6) ('a', 2)