Three Styles for Printing and Concatenating Strings With Python 3.6+

Three Styles for Printing and Concatenating Strings With Python 3.6+

There’s multiple ways to print text to the the console in Python. Here are the three or four ways of doing so. Assuming these variables…

#!/usr/bin/env python3.6
y2k = 2000
legal_drinking_age_us = 21
message = "Python is cool"

…We can print the same string with the same variables with mutltiple styles, starting with the more frowned-upon ways of doing it (#1), and ending with the most superior way (#3)… according to the Googs at least :P . I had always used the first style up until a few weeks ago when I dug into the different approaches.

#1 - OG Style

Combining strings with variables with the + symbol:

print("Y2K was the year " + str(y2k) + "\n" +
      "Legal drinking age in US is " + str(legal_drinking_age_us) + "\n" +
      "and  " + message)
Y2K was the year 2000
Legal drinking age in US is 21
and  Python is cool

#2 - Printf Style

https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting

print("Y2K was the year %s " % str(y2k) + "\n"
      "Legal drinking age in US is %s" % str(legal_drinking_age_us) + "\n"
      "and %s" % message)
Y2K was the year 2000
Legal drinking age in US is 21
and Python is cool

#3 - F-Strings / String Literals (Python 3.6 and above)

https://www.python.org/dev/peps/pep-0498/ These are my new favorite; f-strings! Not only are they easier, but they’re better at working more reliably than using the percentage (%) operand according to the above PEP:

%-formatting is limited as to the types it supports. Only ints, strs, and doubles can be formatted. All other types are either not supported, or converted to one of these types before formatting. In addition, there’s a well-known trap where a single value is passed:

Basically write one big string, and inject variables or call built-in functions when concatenating by enclosing them in curly braces: { }.

One Way

Triple-single-quotes will allow you to write the string in code across multiple lines

print(f'''Y2K was the year {str(y2k)}
Legal drinking age in US is {str(legal_drinking_age_us)}
and {message}''')
Y2K was the year 2000
Legal drinking age in US is 21
and Python is cool

NOTE: Spacing will be taken literally and it could get wacky. See:

print(f'''Y2K was the year {str(y2k)}
       Legal drinking age in US is {str(legal_drinking_age_us)}"
 and {message}''')
Y2K was the year 2000
       Legal drinking age in US is 21"
 and Python is cool

Alternate Way

Meh, I’d rather call the print function just once.

print(f"Y2K was the year {str(y2k)}")
print(f"Legal drinking age in US is {str(legal_drinking_age_us)}")
print(f"and {message}")
Y2K was the year 2000
Legal drinking age in US is 21
and Python is cool

Surely there are other permutations on the same approach, but you get the idea.

Alternate References and Additional Reading