In this exercise, the instructions to create the string returned by the dog_years() function makes it appear like string formatting can be used. How would that be done?
Answer
Instead of using string concatenation and the str() function to produce the output, Python’s string formatting can be used. The following code example shows how to produce the desired output.
def dog_years(name, age):
return "{name}, you are {dog_age} years old in dog years".format(name=name, dog_age=(age * 7))
The idea of this lesson is to replace concatenation with string formatting…
>>> def dog_years(name,age):
dog_years = age * 7
print("{}, you are {} years old in dog years.".format(name, dog_years))
return age * 7
>>> dog_years("Lola", 16)
Lola, you are 112 years old in dog years.
112
>>>
If we are talking about this exercise, it does not require, nor does the “solution” offer old- or new-style string formatting, just concatenation.
I don’t think that any of the Python courses discuss string formatting EDIT: My mistake - Thank you, @fox3773 , except for a bit on the %-style in Python 2. Someone please correct me if I’m wrong.
It’s well worth your while (and quite easy, the basic stuff, at least) to pick it up. Look here, for instance.
The Python 3 course does have 2 exercises covering the .format() string method in lesson 6: strings. I don’t think any other ways to format strings are mentioned, or at least they are never included in any of the exercises.
As @jjpeters1986 mentioned though it is definitely not something that has been covered yet at this point in the coarse.
Even so, I liked how these questions at the end of exercises sometimes touched on concepts or methods / functions, that the coarse had not yet directly covered. This one in particular I happened to find very useful as I absolutely hated concatenating strings together, and I also just think it looks ugly personally. So after seeing this post I was happily using the .format() method far before it is officially covered much later on in the coarse.