In this exercise, the strings for the first and last names are joined using the + operator. Can this be done in another way?
Answer
Yes, string formatting would be another option which could be used to construct a string. The following code example shows a method to produce the same result as the + operator using Python’s string formatting. A new string is constructed using string formatting and is then returned from the function.
Concatenation is not nearly as elegant as string formatting, imho. This way there is only one set of quotes and everything inside can be spaced and punctuated to suit. The example above uses keywords, but we could easily use just placeholders…
"{} {}".format(first_name, last_name)
The old method is modulo formatting,
"%s %s" % (first_name, last_name)
and the newest method is f-string which was introduced in Python 3.6 which uses direct interpolation similar to Ruby and ES6+.
Read up on the various approaches and pick one to use consistently in your work.
No, it doesn’t. Your code throws an error. Mind the “f” directly after your “return” statement. Plus, even if you remove the f, regardless of the input, the output will always be:
{last_name}, {first_name} {last_name}
Apparently you have to add the .format() after the string in order for the code to work the way it should.
It does though you have to assign the value returned by the function call to a variable, then print that variable. I find it interesting because the message variable can be reused later.
For what I understand, the f function converts the 2 parameters to formatted strings. So in the function call you need 2 strings (“John”, “Doe”) as arguments. But if you simply call the function, nothing happens. If you print(introduction), Python prints the location of value returned (i.e: <function introduction at 0x7f3ee41d0e18>).
You’re welcome. Concatenation is a bit of a pill to swallow but once it is understood, should not give you any more problems.
Note also that we can assign and store formatted strings, not just print them.
c = "%s, %s %s" % (var_b, var_a, var_b)
That’s the legacy formatting inherited from C.
c = "{}, {} {}".format(var_b, var_a, var_b)
or,
c = "{2}, {1} {2}".format(var_a, var_b)
or,
c = "{b}, {a} {b}".format(a=var_a, b=var_b)
and the latest version, f-string, which is demonstrated a couple posts above. All of these can be assigned, and will retain the formatting.
Formatting does go one step further in that we can write a format and assign it, then apply it to data later to create the finished string. This is a topic that is worth following up when you have some time to read up and practice with the various methods.